Reputation: 35813
If I have two files, let's call them A.js and B.js:
/src/A.js
/src/B/B.js
A.js uses B.js via ES6 module syntax:
import B from './B/B.js';
and B.js imports other stuff such as:
import http from 'http';
I'm using Babel to convert the module syntax to require
(CommonJS) syntax, and I can run it successfully by doing:
node_modules/babel-cli/bin/babel.js src > compiled.js
However, there's a problem: when I try to run the resulting compiled.js
I get:
/src/b/B.js:1
(function (exports, require, module, __filename, __dirname) { import http from 'http';
SyntaxError: Unexpected token import
The part of the stack trace that comes from compiled.js
points to this line:
var _B = require('./src/b/B')
Although the actual import causing the problem comes from B.js:
import http from 'http';
It seems like the original B.js is being required-in, because the copy of B.js's code inside compiled.js doesn't have an import
, but I don't understand why that version isn't being used.
Any help would be appreciated.
Upvotes: 1
Views: 1164
Reputation: 816780
You don't need to rename any imports. Instead of compiling individual files, compile your whole source folder. This will preserve relative imports.
If your have
src/
A.js
B.js
and run babel src --out-dir lib
, you will get
lib/
A.js
B.js
src/
A.js
B.js
The lib/
folder contains the compiled files. Now you can execute the compiled code via node lib/A.js
and it should work as expected.
Upvotes: 2