6

I have an npm package that I'm writing in ES2015 and transpiling with Babel 6. The ES2015 source code is in /src, split into modules in /src/core, /src/commands, and so on. As it is a CLI tool, the entry point is in /src/bin/app.js. If I run babel-node src/bin/app.js it works as expected.

Ideally, I'd like to install this tool globally (like grunt-cli), so I transpile the whole package to a single, valid JS (ES5) file with babel src -o /lib/app.js. However, if I try to run the file, it raises an error trying to require modules from relative paths, and these modules can't be found because they were all amalgamated into app.js. The error is:

$ node_modules/babel-cli/bin/babel-node.js lib/app
module.js:328
    throw err;
    ^

Error: Cannot find module '../commands/index'
    at Function.Module._resolveFilename (module.js:326:15)
    at Function.Module._load (module.js:277:25)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/app/lib/app.js:19:14)
    at Module._compile (module.js:398:26)
    at Module._extensions..js (module.js:405:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/me/dev/app/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)

My .babelrc is simply:

{
  "presets": ["es2015"]
}

Should this work, or do I need to configure Babel some more? The backup plan is to simply transpile the whole /src folder into /lib and publish everything, but a single file would be nicer.

Louis
  • 146,715
  • 28
  • 274
  • 320
orlade
  • 2,060
  • 4
  • 24
  • 35
  • Duplicate of [this question](https://stackoverflow.com/questions/33963999/using-babel-with-a-single-output-file-and-es6-modules) with referenced answer [here](https://stackoverflow.com/questions/31873235/gulp-concat-and-require-path/33280669#33280669). – orlade Feb 06 '16 at 03:18

1 Answers1

2

Turns out Babel doesn't support this at the moment. It simply concatenates files together, and hence relative path imports won't work.

Rather than using Babel with a path-resolving plugin, the solution is to use Rollup with a Babel plugin. I've created a simple project to test and demo the setup.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
orlade
  • 2,060
  • 4
  • 24
  • 35