巴贝尔有import声明的麻烦

我有一个项目,我正在使用ES6中的节点在使用babel节点运行。 现在我试图以更多的生产方式来实施babel,并尝试了两次尝试。

带有以下configuration的Webpack babel-loader:

module.exports = { entry: './src/cloud/main.js', devtool: 'source-map', output: { path: './src/static/build', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: [ 'babel-loader?presets[]=es2015', ], }, { test: /\.css$/, loaders: [ 'style-loader', 'css-loader', ], }, { test: /\.html$/, loaders: [ 'raw-loader', ], }, ], }, } 

它开始抱怨在main.js中的import语句,并沉默它我用?presets[]=es2015 ,我发现在一个类似的问题。 然后,问题到达,在这个问题中,它被过滤到去往node_modules的导入语句,并带有以下消息:

./~/socket.io/lib/index.js中的错误未find模块:错误:无法parsing模块“fs”in

我的另一种方法是像这样的注册挂钩:

 require('babel-core/register')({ ignore: /node_modules/, }); require('./main.js'); 

但它抛出了这个消息:从“快递”import快递; ^^^^^^

SyntaxError:意外的保留字

//main.js – 简化

 import express from 'express' const app = express() const server = app.listen(port, () => { console.log(`Listening at http://${server.address().address === '::' ? 'localhost' : server.address().address}:${server.address().port}`) }) 

我不认为你需要排除您的加载程序configurationnode_modules 。 但是,您可能想让webpack知道要解决什么问题。 尝试添加这样的东西:

 resolve: { root: path.join(__dirname), fallback: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules'], extensions: ['', '.json', '.js', '.jsx', '.scss', '.png', '.jpg', '.jpeg', '.gif'] }, 

modulesDirectories键应该保持webpack在运行目录中的每一个require / import下运行。

另外,将目标添加到configuration的顶部应该可以解决像fs这样的内置问题

 target: 'node' 

好吧,我想出了其他答案和4m1r答案。 我发布示例代码。

 var path = require('path'); var fs = require('fs'); var nodeModules = {}; fs.readdirSync('node_modules') .filter(function (x) { return ['.bin'].indexOf(x) === -1; }) .forEach(function (mod) { nodeModules[mod] = 'commonjs ' + mod; }); module.exports = { name: 'server', target: 'node', context: path.join(__dirname, 'src', 'cloud'), entry: { server: './main.js' }, output: { path: path.join(__dirname), filename: '[name].js' }, externals: nodeModules, module: { loaders: [ {test: /\.js$/, exclude: /node_modules/, loaders: ['babel-loader?presets[]=es2015']} ] }, resolve: { root: path.join(__dirname), fallback: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules'], } }; 

真正重要的是外部密钥,通过需要和指定的某些原因阻止它泄漏到node_modules中,在babel-loader中?presets[]=2015 。 我正在接受4m1r,因为它终于修复了代码。