使用 pkg 打包 node服务端 项目

前言

最近自己写了一个nodejs+mysql+express 的项目,想着如果项目部署的话还要再安装 node 环境什么的,肯定太麻烦,于是就想有没有像webpack 那样打包项目的插件,于是了解到了 pkg。

了解 pkg原理

pkg实际上并不是直接将程序转换成可执行文件,而是将node环境一起打包到了程序中,这样就可以做到在没有node环境下的电脑上运行node项目了。

安装 pkg
npm install pkg --save-dev
or
npm install pkg -g
pkg的语法
Options:

    -h, --help       output usage information  帮助输出使用信息
    -v, --version    output pkg version --版本输出包装版本
    -t, --targets    comma-separated list of targets (see examples)
    -c, --config     package.json or any json file with top-level config
    --options        bake v8 options into executable to run with them on
    -o, --output     output file name or template for several files
    --out-path       path to save output one or more executables
    -d, --debug      show more information during packaging process [off]
    -b, --build      don't download prebuilt base binaries, build them
    --public         speed up and disclose the sources of top-level project

  Examples:

  – Makes executables for Linux, macOS and Windows
    $ pkg index.js
  – Takes package.json from cwd and follows 'bin' entry
    $ pkg .
  – Makes executable for particular target machine
    $ pkg -t node6-alpine-x64 index.js
  – Makes executables for target machines of your choice
    $ pkg -t node4-linux,node6-linux,node6-win index.js
  – Bakes '--expose-gc' into executable
    $ pkg --options expose-gc index.js
步骤

1.首先在我们的 node 项目中的 package.json里做配置

  "scripts": {
    "start": "hotnode index.js",
    "pkg": "pkg . --out-path=dist/",//需要打包时直接终端输入 npm run pkg
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "bin":"./index.js",//打包的入口文件
  "pkg": {
    "scripts": "build/**/*.js",
    "assets": "views/**/*",//需要打包的静态文件目录
    "targets": ["node8"]//打包的类型
  },

2.终端输入命令

npm run pkg

3.耐心等待完成后,项目中会出现 dist 文件夹,里面的 server 就是一个二进制可执行文件,双击就可以启动 node 项目了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值