title: 65.内网制作npm包 CreateTime: 2020-12-07 22:00:00 UpdateTime: 2020-12-07 22:00:00 CategoryName: web --- --- title: "65.内网制作npm包" date: 2020-12-07T22:00:00+08:00 draft: false tags: ["web"] categories: ["web"] author: "springrain" --- ## 1. 环境说明 因为公司环境特殊,无法连接任何互联网,不能使用proxy模式搭建npm仓库,前端VUE项目的node_modules是下载好的源文件. 使用shell脚本,重新打包 node_modules,npm publish 上传npm的tgz包. ## 2. 打包的shell脚本 ```shell #!/bin/sh ###使用root账户执行脚本,参数:需要打包的node_modules路径### ###准备: npm login ,npm install -g npm-pack-all(配合设置环境变量),npm config set registry http://npm内网仓库IP:端口/repository/仓库名称/ ### ###因为是二次打包,会出现异常,例如 ERR! code EINTEGRITY, 删除 package-lock.json ,执行 npm cache verify -g, npm cache clean --force , 然后再执行: npm install ### ###参数:需要上传的node_modules目录 baseDir=$1 ###遍历文件 listFiles(){ ##遍历参数传递的目录 for file in `ls $1`; do ##如果目录下有package.json文件,认为是一个前端模块 if [ -e "$1/$file/package.json" ]; then ##进入临时目录 cd $baseDir/.npmtgztemp/ ##删除软连接,因为模块打包必须是叫package文件夹 rm -rf package ##创建软链接 ln -s $1/$file ./package ##打包 tar -czf $file.tgz package/* ##发布,需要npm login 和npm config set registry ... npm publish $file.tgz --registry http://npm内网仓库IP:端口/repository/仓库名称/ >/dev/null 2>&1 ##如果发布失败,使用npm publish 源码发布 if [ $? -ne 0 ]; then ##使用npm publish 发布 echo "模块:$file.tgz包发布失败,使用源码发布" cd $baseDir/.npmtgztemp/package npm publish --registry http://npm内网仓库IP:端口/repository/仓库名称/ >/dev/null 2>&1 if [ $? -ne 0 ]; then echo "模块:$file 源码发布失败,尝试使用 npm-pack-all " npm-pack-all --output $file-pack.tgz --registry http://npm内网仓库IP:端口/repository/仓库名称/ >/dev/null 2>&1 npm publish $file-pack.tgz --registry http://npm内网仓库IP:端口/repository/仓库名称/ >/dev/null 2>&1 if [ $? -ne 0 ]; then echo "---------------------------------------------模块:$file 发布失败---------------------------------------------" else echo "模块:$file npm-pack-all发布成功" fi ##删除npm-pack-all生成的文件,避免影响原始目录 rm -rf $file-pack.tgz else echo "模块:$file 源码发布成功" fi else echo "模块:$file.tgz 发布成功" fi ##如果有依赖包,把依赖包也上传 if [ -d "$1/$file/node_modules" ]; then listFiles "$1/$file/node_modules" fi ##如果是目录,递归循环 elif [ -d "$1/$file" ]; then listFiles "$1/$file" ##如果是文件,输出记录 #else #echo "文件:$file" fi ###删除临时目录 #rm -rf $baseDir/.npmtgztemp done } ###删除临时目录 rm -rf $baseDir/.npmtgztemp ###创建临时目录 mkdir -p $baseDir/.npmtgztemp/package ###调用函数,传入参数 listFiles $1 ``` ## 3.Jenkins Build脚本 ```shell #!/bin/sh ###需要一个参数:vue项目的根目录 ###Vue项目根目录 baseDir=$1 ##进入到项目根目录 cd $baseDir ##删除掉历史生成的dist目录 rm -rf dist ##如果svn或git中有node_modules目录,不使用 npm install if [ ! -d "$baseDir/node_modules" ]; then rm -rf package-lock.json npm cache verify npm install fi ##.bin执行权限 if [ -d "$baseDir/node_modules/.bin" ]; then chmod 755 $baseDir/node_modules/.bin/* fi ##执行生产环境编译 npm run build --prod ##打包,忽略dist的一层目录,避免解压的时候是dist目录 tar -czf dist.tar.gz --transform s=dist/== dist/* ```