前端工程化初探 CI 流程
包管理
统一使用 cnpm
CI流程
公司使用的是Tekton来代替原来的Gitlab CI(云原生、轻量级、扩展性好、有API接口,GitHub社区ok),以下步骤会在Tekton中执行:
1. 静态代码检测
命令:
1 | cnpm run lint |
说明:
- 使用 ESLint 进行静态代码检测,规范暂未统一,推荐使用 Airbnb 或 Standard 的标准(接入说明),和插件。
- 使用 SonarQube 进行其他规范的检测。
cnpm run lint
package.json中需要添加:1
2
3"scripts": {
"lint": "eslint -f json -o reports/eslint.json src/.",
},
- lint:在
/reports
目录下生成eslint.json
文件,用于之后 sonar 检测时读取的结果文件。
cnpm run lint-html
package.json中需要添加:1
2
3"scripts": {
"lint-html": "eslint -f html -o reports/index.html src/.",
},
- lint-html:在
/reports
目录下生成index.html
文件,eslint 报告的UI界面。 - 如果/reports已经存在于项目中有其他用途,可以统一换一个名称
- sonar
这一步无需配置,只要保证前面的reports/eslint.json
文件成功生成就行。
可在本地安装 sonar 进行测试:默认会检测在1
2
3
4
5sonar-scanner
-Dsonar.projectKey=fe-project
-Dsonar.sources=./src
-Dsonar.host.url=http://39.100.144.36
-Dsonar.eslint.reportPaths=reports/eslint.json./src
目录下的代码,如果前端代码不在这个目录下需要另寻统一方法
Artifacts:
reports
├── eslint.json
└── index.html
2. 单元测试
命令:
1 | cnpm run test |
说明:
使用 Jest
进行单元测试,接入指南。
使用 Allure
配合 Jest
实现单测结果的展示。
cnpm run test
package.json中需要添加:1
2
3"scripts": {
"test": "jest --coverage --all -o",
},在
/coverage
目录下生成覆盖度报告allure generate --clean
2.1 生成Allure
的报告,需要安装jest-allure
:cnpm i -D jest-allure
- 在 jest.config.js 配置文件中添加:配置完后每次运行 cnpm run test 就会在 /allure-results 目录下生成结果,用于之后的步骤。
1
2
3
4
5module.exports = {
testEnvironment: 'jsdom',
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
setupFilesAfterEnv: ['jest-allure/dist/setup'],
}
2.2 生成
Allure
报告的 UI 界面
需要安装allure
(仅为了在本地跑通,也可以跳过,只要确保上一步的/allure-results生成即可)
Mac OS:1
brew install allure
或:
直接下载,然后配置 $PATH
在项目根目录下运行:1
allure generate --clean
在 /allure-report 目录下生成html文件
Artifacts:
coverage
├── clover.xml
├── coverage-final.json
├── lcov-report
└── lcov.info
allure-results
├── 2ed4135f-5ef3-4009-a9f0-bdc191e94680-testsuite.xml
allure-report
├── index.html
├── styles.css
3. 项目打包
命令:
1 | cnpm run build |
说明:
cnpm run build
打包package.json
中需要添加:这一步只需要保证打包完后的结果生成在 /build 目录下,如果原先默认是 /dist 之类的需要修改下配置。1
2
3"scripts": {
"build": "你的打包指令",
},cnpm run upload-static
上传静态资源文件到又拍云或别的什么云,统一指令为 upload-static 就行。
package.json 中需要添加:如果是又拍云可以用以下方法:1
2
3"scripts": {
"upload-static": "upyun-upload -c tool/upyun-static.config.js -v",
},
安装upyun-upload
,前人留下的轮子。
在 /tool 目录下创建upyun-static.config.js
文件:1
2
3
4
5
6
7
8
9
10
11
12const join = require('path').posix.join
module.exports = {
operator: 'crm',
password: 'Gold Miner',
tasks: [{
prefix: 'miqi-static/',
endpoint: 'v0',
bucket: 'bxsls',
directory: join(__dirname, '../build/static')
}]
}
console.log('url: s.sls.baixing.net/ + filename')
Artifacts:
build (内容不定)
├── asset-manifest.json
├── favicon.ico
├── index.html
├── robots.txt
└── static
生成一堆报告后别忘了在.gitignore里添加:
/reports
/coverage
/allure-results
/allure-report
/.scannerwork
Dockerfile
静态页面只要 Nginx
默认使用在 CI 中生成的 ./build 目录
1 | FROM nginx:1.18.0 |