背景: 使用webpack打包nodejs服务,并部署到线上。
webpack 打包
自己的项目中是可以不用这个,因为都是使用nodejs开发。
const path = require("path")
const fs = require("fs");
const nodeModules = {};
fs.readdirSync("node_modules")
.filter(function(x) {
return [".bin"].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = "commonjs " + mod;
});
module.exports = {
mode: 'production',
entry: './server.js',
output: {
path: path.resolve(__dirname, "dist"),
filename: "musicServer.js",
chunkFilename: "[name].chunk.js",
libraryTarget: "commonjs"
},
node: {
fs: 'empty',
child_process: 'empty',
tls: 'empty',
net: 'empty'
},
target: "node",
externals: nodeModules,
};
externals 是不许设置的。因为 这样打包的话,一些 npm 中的模块也会被打包进这个 musicServer.js,还有 node 的一些原生模块,比如 fs/path 也会被打包进来,这明显不是我们想要的。所以我们得告诉 webpack,你打包的是 node 的代码,原生模块就不要打包了,还有 node_modules 目录下的模块也不要打包了。
线上部署
一般在linux是部署,常用 nohup command > out.log 2>&1 &
进行部署,但是用在nodejs服务上时,关掉终端terminal后,nodejs 服务就自动关掉。
(nohup命令:如果你正在运行一个进程,而且你觉得在退出帐户时该进程还不会结束,那么可以使用nohup命令。& : 指在后台运行)
常用解决的方案有一些,见参考文章。本初使用 pm2
进行管理,使用方法见参考文章。
安装pm2
npm install -g pm2
由于nodejs服务,依赖一些modules,所以需要安装相应的modules,使用modules有两种如下两种方式:
1使用局部modules
首先安装 局部modules
进入项目包含 package.json 目录,执行命令:
npm install
然后启动服务:
pm2 start server.js
关闭终端后,服务仍正常运行。
pm2 list
可以查看pm2 启动的并正在运行的服务。
2 使用全局modules
查看全局modules
npm list -g --depth 0
不加 --depth 0
会显示更多层级。
设置环境变量,以便能搜索到modules
export NODE_PATH=/usr/local/lib/node_modules
注:只在该shell终端有效。
node_modules 的路径在不同系统上可能会有差别,请根据实际情况配置。同时可以将该配置加入到 profile中,使其一直生效。
启动服务
pm2 start server.js
这种方法,回到值局部
参考文章:
xshell一退出,nodejs项目就停止 https://segmentfault.com/q/1010000004590993
pm2常用的命令用法介绍
https://blog.csdn.net/chengxuyuanyonghu/article/details/74910875
Linux 命令详解(一)export 命令 https://www.cnblogs.com/tinywan/p/7224011.html?utm_source=itdadao&utm_medium=referral
用 webpack 构建 node 后端代码,使其支持 js 新特性并实现热重载 https://zhuanlan.zhihu.com/p/20782320?from=singlemessage&isappinstalled=0&utm_source=wechat_session&utm_medium=social