应用pkg打包node项目

如今公司有以私有部署增加营收的打算,于是便着手开始对所负责项目进行一键打包。

pkg简述

既然是私有部署,自然需要做到易于部署,保护代码,易于维护。

https://github.com/zeit/pkg

pkg便能满足这些需求

This command line interface enables you to package your Node.js project into an executable that can be run even on devices without Node.js installed

首先看一下官方的简介,pkg能将node.js项目打包成一个不需要node环境就可以运行的可执行文件

pkg使用

这里直接使用package.json 进行打包(当然也可以针对js文件直接进行打包,此处不做赘述),

"bin": "index.js",//项目启动文件

"pkg": {"scripts": "build/**/*.js","assets": "views/**/*" } //需要额外打包进去的目录

在package.json中增加这段,scripts,assets配置未打包进可执行文件的js/json 文件及其他资源文件,文件路径可以使用glob通配符

这是由于pkg只会自动打包require或__dirname的文件(如下),其余文件需手动配置

require('./build/'+cmd+'.js')

path.join(__dirname,'views/'+viewName)


之后使用以下命令即可打包,

pkg .  --target node8-linux --out-path package

(使用node8版本打包一个linux可运行文件,放入package文件夹中,详细参数参见https://github.com/zeit/pkg/blob/master/README.md)

同时需要的是,打包进可执行文件中的文件,以下的系统文件路径发生了变化。因此如有必要,需要对文件地址进行调整。

注意事项

以下是实际打包中遇到的一些问题及解决方法,

1.pkg无法识别引用的变量地址

require('./test/'+ test +'.js')

由于路径不是常量,pkg无法识别要打包的文件是什么,因此尽量将引用地址写为常量地址

如果node_modules里的文件引用存在该现象怎么办呢?

笔者这次便遇到了这个问题,于是采用改写node_modules相关类库相关文件,通过patch-package进行补丁打包,请参考 https://github.com/ds300/patch-package#readme

2.pkg无法打包Native addons (.node files) 

Native addons (.node files) use is supported, but packaging .node files inside the executable is not resolved yet. You have to deploy native addons used by your project to the same directory as the executable.

看一下官方的处理方法,把这类文件拿出来放在可执行文件相同的目录里。

3.配置文件外部挂载,方便运维维护

对config的引用进行处理

var fs =require('fs');

try {

var configJson =JSON.parse(fs.readFileSync(

process.cwd() +'/config.json',

  'utf-8'));

}catch (e) {

  configJson =null;

}

var config =configJson ?configJson :require('./config.json');

exports.config =config;

优先读取挂载在外部的配置文件,如果不存在再读取pkg内部的快照文件,如此便实现了外部挂载,

方便运维对配置文件进行修改。

你可能感兴趣的:(应用pkg打包node项目)