目录

webpack打包nodejs后端代码配置可独立修改方案

webpack打包nodejs后端代码配置可独立修改方案

工具: webpack + nodebyte

1. 安装第三方模块

npm i webpack
npm i -g -S nodebyte

2. 根目录下创建webpack.config.js文件

const path = require('path');
 
module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build')
  },
  target: 'node' ,
  output: {
    libraryTarget: 'commonjs',
  },
  externals: [
    /^(?!|\/).+/i,
  ]
}

3. 添加命令至package.json方便后续打包

"scripts": {
    "build": "webpack",
    "build2": "bytenode --compile ./dist/main.js"
  },

4. 创建static目录,将原配置文件config.js复制一份副本放在该目录下

目录结构如下:

|—config

| |—config.js

|—static

| |—config.js

5. 修改两个config.js

  • static/config.js 正常编写配置
module.exports = {
    "api": {
        "address": "0.0.0.0",
        "port": "13000"
    },
    "mongodb": {
        "url": "mongodb://192.168.0.26:27017/test"
    }
};
  • config/config.js 使用fs读取static下配置
const Fs = require('fs');
let configfile = Fs.readFileSync('./static/config.js','utf-8').toString();
let index = configfile.indexOf("=")
let configStr = configfile.substring(index + 1);    
configStr = configStr.substring(0,configStr.length - 1)   //去掉最后的;号
let config = JSON.parse(configStr)
module.exports = config

因为webpack会将require或import的js全部打包在一起,所以采用fs读取配置的方式。其他js文件引用config/config.js中的配置即可。

6. 打包

npm run build 使用webpack进行打包,打包为一个main.js文件

npm run build2 将main.js转为字节码文件main.jsc

7. 运行

  • 方式一: 直接使用bytenode ./dist/main.jsc运行项目
  • 方式二:
    • 先编写运行文件index.js

      require('bytenode');
      require('./dist/main.jsc');
    • 再node运行index.js或使用pm2运行index.js