babel-node es6 “Modules aren't supported in th

2019-02-23 15:46发布

问题:

babel-preset-es2015 is installed, and is OK with es6 feature just like below let a = 2;.
But can not work with es6 modules feature import fs from 'fs' as following:

$ babel-node --presets es2015
> let a = 2;
'use strict'
> a
2
> import fs from 'fs';
SyntaxError: repl: Modules aren't supported in the REPL
import fs from 'fs';  
    at File.buildCodeFrameError (/usr/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:407:15)
    at NodePath.buildCodeFrameError (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/path/index.js:149:26)
    at PluginPass.ModuleDeclaration (/usr/lib/node_modules/babel-cli/lib/_babel-node.js:78:20)
    at newFn (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/visitors.js:262:19)
    at NodePath._call (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/path/context.js:63:18)
    at NodePath.call (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/path/context.js:47:17)
    at NodePath.visit (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/path/context.js:93:12)
    at TraversalContext.visitQueue (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitMultiple (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/context.js:110:17)
    at TraversalContext.visit (/usr/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/context.js:182:19)

So what's wrong?
Thanks!

回答1:

The error message is exactly what it says. You cannot use ES6 module syntax in the REPL, it is unsupported. You can create a small adapter that imports as ES6 and exports as CommonJS:

# es6-to-common.js
import MyThing from './somewhere';
module.exports = MyThing;

Now inside your usual babel-node prompt:

> MyThing = require('./es6-to-common')


回答2:

Got it from the official doc:http://babeljs.io/docs/usage/cli/

ES6-style module-loading may not function as expected
Due to technical limitations ES6-style module-loading is not fully supported in a babel-node REPL.