先说一下背景,所以作者所在组织的前端项目使用了自定义的前端组件,放在了cnpm搭建的仓库中,由于人员变动,源代码已经丢失,仓库也被销毁,只留了打包好的库,所以每次打包都非常麻烦,再加上使用了node-sass包,对node版本要求特别高,原来打包在jenkins主机上使用npm命令来打包,非常容易出错。后面我改用使用docker容器,使构建的环境每次都一样,避免了打包失败的情况。现在说一下步骤。
首先构建一个打包镜像,Dockerfile文件如下
FROM node:11
WORKDIR /user/app
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set sass_binary_site=https://registry.npmmirror.com/binary.html?path=node-sass/
RUN npm config set cache '/user/app/node_cache'
COPY entrypoint.sh .
RUN chmod +x entrypoint.sh
ENTRYPOINT ["/user/app/entrypoint.sh"]
这里说明一下,这边使用了基础镜像node:11,版本是根据需要来的,你也可以自己修改,npm config set都是设置node的变量,加速构建过程,RUN npm config set cache是设置了node的缓存位置,构建的时候,把这个缓存位置映射到主机上,加快下次构建。entrypoint.sh是构建的脚本,以贴出来
#!/bin/bash
cd 代码位置
npm install
npm run build
echo "完成构建"
sleep 3
构建一下镜像
docker build -t node-build:11 .
然后运行容器
docker run -v 代码位置:/user/app/代码项目 -v /home/deng/web/node:/user/app/node_cache -it --rm node-build:11
如果这样没问题,就可以在看到构建的程序了
正常打包代码就这样结束 ,但是也可以直接把node_modules包直接打到镜像里头去,这样构建的脚本就不要使用npm install。让打包镜像的dockerfile就可以修改成这样
FROM node:11
WORKDIR /user/app
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set sass_binary_site=https://registry.npmmirror.com/binary.html?path=node-sass/
RUN npm config set cache '/user/app/node_cache'
ADD node_modules.tar.gz /user/app
COPY entrypoint.sh .
RUN chmod +x entrypoint.sh
ENTRYPOINT ["/user/app/entrypoint.sh"]
注意ADD node_modules.tar.gz /user/app,这个命令就是把node_modules压缩包放到容器目录中去,ADD命令会自动解压。
entrypoint.sh改成这样
#!/bin/bash
mv node_modules ./代码位置/node_modules
cd 代码位置
npm run build
echo "完成构建"
sleep 3