Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel compiled JS fails to import relative paths

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.

like image 846
orlade Avatar asked Feb 05 '16 08:02

orlade


1 Answers

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.

like image 163
orlade Avatar answered Oct 31 '22 02:10

orlade