【发布时间】:2020-06-08 02:25:33
【问题描述】:
我正在尝试使用 express 制作节点后端服务,并且我也想使用 webpack 将所有内容捆绑在一个文件中(不知道是否有意义,我只是在学习)。我这样设置了我的package.json:
{
"name": "something",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js --mode=production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"express": "^4.17.1"
}
}
这是我的webpack.config.js 文件:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const backend = {
name: 'backend',
target: 'node',
devtool: 'source-map',
externals: [nodeExternals],
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'bin'),
filename: 'app.js'
}
};
module.exports = [backend];
module.exports.plugins = [
new webpack.SourceMapDevToolPlugin({})
];
这是我的src/index.js:
var express = require('express');
var httpsrv = express();
httpsrv.get("/", function(res, rep) {
console.log("inside get.");
rep.send("<div>hey js!</div>");
});
httpsrv.listen(8080, function() {
console.log("server started.");
});
非常基本,不是吗?当我构建并运行 (node ./bin/app.js) 应用程序时,一切都很好,它的行为符合预期,但听起来我很奇怪。 app.js 文件太短,无法捆绑 express 库,当我将 app.js 放入 node:alpine 容器时,我收到此错误:
internal/modules/cjs/loader.js:1032
throw err;
^
Error: Cannot find module 'express'
Require stack:
- /app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1029:15)
at Function.Module._load (internal/modules/cjs/loader.js:898:27)
at Module.require (internal/modules/cjs/loader.js:1089:19)
at require (internal/modules/cjs/helpers.js:73:18)
at Object.<anonymous> (/app.js:1:1134)
at n (/app.js:1:110)
at Object.<anonymous> (/app.js:1:958)
at n (/app.js:1:110)
at /app.js:1:902
at Object.<anonymous> (/app.js:1:911) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/app.js' ]
}
所以我没有得到我想要的:单个文件中的 Web 服务。这里有什么问题?
【问题讨论】:
-
你有什么理由要 webpack 你的服务器端代码吗?我不明白你为什么需要它
-
我建议不要这样做。我之前考虑过为自己的项目做这件事,调试中的损失牺牲不值得你可能寻求的微不足道的性能提升
标签: javascript node.js express webpack