gpt4 book ai didi

javascript - 如何设置 webpack 以支持 Node 中的 ES6 模块

转载 作者:行者123 更新时间:2023-11-30 06:51:11 24 4
gpt4 key购买 nike

我使用 Webpack 来捆绑客户端和服务器代码,所以我的 webpack.config.js 看起来像:

module.exports = [
{ /* client config */ },
{ /* server config */ },
];

我想在两者中编写 ES6(模块)并使用 Babel 将代码转换为 ES5。

对于客户端,这可以通过 babel-loader 完成:

{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [
'react',
[
'env',
{
targets: {
'browsers': 'last 2 versions',
},
},
],
],
},
}

基于此,我写了服务器的babel loader:

{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [
'react',
[
'env',
{
targets: {
'node': 'current',
},
},
],
],
},
}

Something tells me that babel-loader will never work for this purpose.

运行 webpack 后,包位于正确位置,但服务器入口点 (server.js) 未正确转译:

语法错误:意外的 token 导入

一般我们要转译Node代码时,会使用babel-cli包,在package.json中添加脚本:

"scripts": {
"build": "babel src -d dist"
}

和手动:

npm 运行构建

我的问题是:如何在 webpack.config.js 中使用 Babel for Node 设置 ES6 转译?


+奖金

webpack.config.js

const path = require('path');

const babelRcClient = {
presets: [
'react',
[
'env',
{
targets: {
'browsers': 'last 2 versions',
},
},
],
],
};
const babelRcServer = {
presets: [
'react',
[
'env',
{
targets: {
'node': 'current',
},
},
],
],
};

const babelLoaderClient = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: babelRcClient,
};
const babelLoaderServer = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: babelRcServer,
};

module.exports = [
{
context: __dirname,
entry: './shared/index.js',
output: {
path: path.resolve(__dirname, './static'),
filename: 'bundle.js',
},
module: {
loaders: [
babelLoaderClient,
],
},
plugins: [],
},
{
context: __dirname,
entry: './server/server.js',
target: 'node',
output: {
path: path.resolve(__dirname, './build'),
filename: 'server.js',
libraryTarget: 'commonjs',
},
externals: [ /^(?!\.|\/).+/i, ],
module: {
loaders: [
babelLoaderServer,
],
},
plugins: [],
},
]

最佳答案

通过指定

targets: {
'node': 'current',
}

你告诉 babel 将你的代码转换为你用来转换代码的 node 版本。

您是否在生产环境中使用相同的 Node 版本?

尝试指定数字 node 版本,例如6.11.2 然后运行转译。

您可以做的另一件事是通过设置告诉 babel 以 ES6 方式保留 ES6 模块并且不要用 commonjs 方法(默认)替换它:

targets: {
'node': ...,
},
modules: false

关于javascript - 如何设置 webpack 以支持 Node 中的 ES6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46672639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com