My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Don't put ES6 code in npm, for now

Jon's photo
Jon
·May 27, 2016

Using Mocha and ES6,

mocha --require react-native-mock/mock.js --compilers js:babel-core/register --recursive test/**/*.js

I got this error:

import createIconSet from './lib/create-icon-set';
^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:513:28)
    at Module._extensions..js (module.js:550:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/chen/repo/supplychain/beaconRN/node_modules/babel-core/node_modules/babel-register/lib/node.js:166:7)

After some searching I noticed Babel does not handle ES6 code in node_modules/, which uses .js as an extension:

http://stackoverflow.com/a/35045012/883571

And the code proved the behavior:

https://github.com/babel/babel/blob/master/packages/babel-register/src/node.js#L87

function shouldIgnore(filename) {
  if (!ignore && !only) {
    return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
  } else {
    return util.shouldIgnore(filename, ignore || [], only);
  }
}

function loader(m, filename) {
  m._compile(compile(filename), filename);
}

function registerExtension(ext) {
  let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
}

Our toolchains is too complicated driven by the eager of Facebook. Just don't make it worse by putting Babel in node_modules.