1

Is there a way to import native Node modules (e.g. crypto, fs, path) when using Babelify with Browserify?

For example:

'use strict'; import $ from 'jquery'; import fs from 'fs'; // <------ this line causes an error var data = JSON.parse(fs.readFileSync('foo.json', 'utf8')); $(document).ready(function () { // stuff }); 

Browserify gives me this error when I try to run it:

Error: tried to statically call { readFile: [Function: readFile], readFileSync: [Function: readFileSync], readdir: [Function: readdir], readdirSync: [Function: readdirSync] } as a function while parsing file: /home/vincent/www/project1/resources/js/foo.js while parsing file: /home/vincent/www/project1/resources/js/foo.js

I've also tried the following with the same results:

import * as fs from 'fs'; import { fs } from fs; 
5
  • I think that primarily depends on how the module is exporting the values. Commented Jan 5, 2016 at 5:22
  • @FelixKling Ok but neither jquery nor fs export any modules so why does Babelify only pick up jquery? Commented Jan 5, 2016 at 5:24
  • Uh? Of course fs exports something, it is a module after all. Looking at its source, it does something similar to exports.foo = 42;, so import * as fs from 'fs'; should work IMO. This may help: 2ality.com/2015/12/babel-commonjs.html Commented Jan 5, 2016 at 5:32
  • @FelixKling Oh I thought you meant export as in the ES6 export. Anyways I found out that it doesn't work due to breaking static analysis: github.com/babel/babelify/issues/81 Commented Jan 5, 2016 at 5:38
  • Ah right. Importing is not the issue, but usage with browersify. Commented Jan 5, 2016 at 5:42

1 Answer 1

3

This is a known issue with brfs and Babelify:

It will eventually be possible once static-module can handle ES6 imports. For now you need to 'require' brfs with CommonJS syntax, and run the brfs transform after babelify.

Sources:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.