我使用的WebPack用於捆綁客戶端和服務器代碼支持ES6模塊,所以我webpack.config.js
樣子:如何設置的WebPack在節點
module.exports = [
{ /* client config */ },
{ /* server config */ },
];
我想寫的都和transpile ES6(模塊)代碼到ES5使用Babel。
對於客戶端,這可以用babel-loader
完成:在此基礎上
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [
'react',
[
'env',
{
targets: {
'browsers': 'last 2 versions',
},
},
],
],
},
}
,我寫了巴貝爾裝載機服務器:
{
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
)沒有正確傳輸:
SyntaxError: Unexpected token import
一般來說,當我們想transpile節點的代碼,我們將使用babel-cli
封裝,package.json
添加腳本:
"scripts": {
"build": "babel src -d dist"
}
和手動:
npm run build
我的問題是:如何在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: [],
},
]
你運行偶然的出處嗎?根本不應該有任何導入語句,webpack不僅會處理'import' /'export'開箱即用,而且當前的Babel配置會在傳遞到webpack之前被轉發出去(最好離開'輸入'到webpack,而不是將它們轉換)。 –
@MichaelJungo對不起,你的意思是關於「將import導入webpack而不是轉發它們」? –
我注意到你正在使用webpack v1。我認爲這不支持「輸入」 - 也許這裏存在問題。我找不到那個來源,但我想我今天讀到了這個。我會盡力找到源代碼,但在此期間,您可以嘗試碰撞webpack或包含某種裝載程序。 – Morishiri