所需行为
我希望能够:
webpack
定义使用babel
将ES6服务器端节点文件转换为"plain javascript"
当前行为
如果我刚跑:
node app.js
我收到导入错误:
从“快递”进口快递; ^^^^^^^
SyntaxError:意外的标识符
我尝试过什么
当我尝试在webpack中定义构建过程时,我会遇到如下错误:
无法解决
tls
/net
/fs
/dns
/child_process
/aws-sdk
/./local_settings
/npm
/ {{ 1}}
提供了一个可能的解决方案here,但它并未解决所有错误(这些错误仍然存在:node-gyp
,aws-sdk
,./local_settings
,{{1} }):
npm
还有警告:
模块解析失败:意外的令牌
关键依赖:依赖的请求是表达式
这“我如何在生产中使用ES6?”问题似乎很常见,例如:
NodeJS in ES6/ES7, how do you do it in production?
Quickstart guide to using ES6 with Babel, Node and IntelliJ
Getting ready for production use
Is it okay to use babel-node in production
但我发现的答案似乎都没有明确或特别与webpack解决方案相关。
以下是我现在的代码:
来自node-gyp
target: "node"
来自webpack.config.js
:
const path = require('path');
console.log("the __dirname is: " + __dirname);
module.exports = {
entry: "./src/js/app.js",
output: {
filename: "app.js",
path: path.resolve(__dirname, "dist/js")
},
target: "node",
mode: "development",
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "stage-0"]
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.less$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "less-loader" }
]
},
{
test: /\.jpg$/,
use: [
{ loader: "url-loader" }
]
}
]
}
}
问题
为了成功将ES6文件转换为package.json
,我的 ...
"main": "app.js",
"scripts": {
"start": "nodemon ./app.js --exec babel-node -e js",
"build": "webpack",
"watch": "webpack --w"
},...
"dependencies": {
"bcrypt": "^2.0.1",
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.3",
"jsonwebtoken": "^8.2.1",
"mongodb": "^3.0.8"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"less": "^3.0.4",
"less-loader": "^4.1.0",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3"
}
和webpack.config.js
文件应该是什么样的?
答案 0 :(得分:2)
默认情况下,Webpack会尝试将所有内容捆绑到一个.js
文件中。对于客户端项目,这很好,但对于NodeJS项目,它变得稍微复杂一些,因为你也包括来自node_modules
的代码。有时,这会导致您在此处看到的错误。
除targets: "node"
之外,您要做的是告诉Webpack 不捆绑外部依赖项(即node_modules
)。
有一个名为webpack-node-externals的有用库可以帮助解决这个问题:
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
所以它并不是真正的"普通的javascript",更像是试图让Webpack输出一个与NodeJS生态系统兼容的文件。