javascriptnode.jsecmascript-6babeljsbabel-preset-env

Babel-register working in the package but not when require-ing the package


I've set up babel-register in my package (installed "babel-preset-env": "1.7.0", "babel-register": "6.26.0")

index.js

require('babel-register');

// Contains a bunch of `import * ` stuff.
const lib = require('./lib.js');

.babelrc

    {
    "presets": [
        "env"
    ]
}

This works just fine locally, but when i publish my package and try to use it I still get the:

SyntaxError: Unexpected token import
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (internal/modules/cjs/loader.js:618:28)

Solution

  • babel-register is a global singleton module, which means only one instance of it can be in use at one time. Given that, the expectation is that only the top-level application being developed would be using it. To align with those goals, babel-register automatically ignores all files inside node_modules, since the assumption is that node_modules will already be compiled to work on the user's node version before it was published.

    The reason your logic fails when installed is because of the automatic exclusion of node_modules, since your module is installed into node_modules.

    Even if that were not the case though, your usage here also runs into issues because of the global singleton behavior I mentioned above. If you load babel-register here, it will automatically try to compile the code of the user using your library to, which they have not asked for, are not expecting, and may fail.

    You should compile your library code before publishing it.