reactjs,browserify,ecmascript-6,babel , Babelify omit file extension on import


Babelify omit file extension on import

Question:

Tag: reactjs,browserify,ecmascript-6,babel

I am writing a React application with ES6 and JSX. Below is the command I use to browserify my .es6 files into a bundle.js.

$ browserify src/es6/app.es6 -t babelify -o build/js/bundle.js

When I try to import a component using something like import MenuBar from './menu', I get the error message:

Error: Cannot find module './menu'

The only workaround I found is adding .es6 to the file name (import MenuBar from './menu.es6'), which isn't very appealing to look at.

Is there a way to let browserify or babelify know which extensions to use when importing modules?


Answer:

Try:

browserify src/es6/app.es6 -t babelify -o build/js/bundle.js \
--extension=.js --extension=.json --extension=.es6

Babelify should handle .es6 by default on its end.

By the way, if you can you're often better off writing scripts against the browserify API rather than using the CLI. In this case it'd be something like:

var
  browserify = require('browserify'),
  babelify = require('babelify'),
  path = require('path'),
  fs = require('fs');

browserify('src/es6/app.es6', {
  extensions: ['.js', '.json', '.es6'],
})
  .transform(babelify)
  .bundle()
  .pipe(fs.createWriteStream(path.join(__dirname, 'build/js/bundle.js')));

Related:


What is the proper way to get the value of a React