如何借助GitHub Action自动移除Angular+WordPress项目的console.log()?
自动移除Angular项目中的console.log(部署/提交GitHub时)
方案1:利用Angular生产构建自带的优化
Angular在生产模式下(Angular 12+用--configuration production,旧版本用--prod),默认会通过Terser压缩代码并剔除console.log(默认保留console.error和console.warn)。
直接在GitHub Action的构建步骤中使用以下命令即可:
ng build --configuration production
若要确认配置生效,可打开angular.json检查生产配置中的optimization是否设为true:
"configurations": { "production": { "optimization": true, // 其他默认配置... } }
方案2:自定义Terser配置彻底移除所有console
如果需要连console.error和console.warn一并移除,可通过自定义webpack配置实现:
- 在项目根目录新建
extra-webpack.config.js文件:
module.exports = { optimization: { minimizer: [ new (require('terser-webpack-plugin'))({ terserOptions: { compress: { drop_console: true, // 移除所有console语句 }, }, }), ], }, };
- 修改
angular.json的build配置,引入上述自定义文件:
"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "customWebpackConfig": { "path": "./extra-webpack.config.js" }, // 其他配置... } }
后续执行生产构建时,所有console语句都会被清除。
方案3:提交代码前自动处理(避免脏代码进入仓库)
若想在git commit阶段就清除console.log,推荐使用ESLint+husky的组合:
- 在
.eslintrc.json中启用no-console规则:
"rules": { "no-console": "warn" }
- 在
package.json中添加自动修复脚本:
"scripts": { "lint:fix": "ng lint --fix" }
- 安装husky和lint-staged依赖:
npm install husky lint-staged --save-dev
- 在
package.json中配置提交钩子:
"husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.ts": ["npm run lint:fix", "git add"] }
此后每次提交代码前,工具会自动修复TS文件中的console.log问题,并将修复后的代码提交至仓库。
若要在GitHub Action中重复该检查,可在工作流中添加对应步骤:
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - run: npm ci - run: npm run lint:fix - run: ng build --configuration production # 此处添加你的部署步骤(如上传至服务器)
方案4:WordPress后端JS文件的处理
如果你的WordPress主题/插件包含自定义JS文件,可使用Terser手动处理:
npx terser wp-content/themes/your-theme/js/custom.js --compress drop_console=true -o wp-content/themes/your-theme/js/custom.min.js
将该命令添加至GitHub Action的步骤中,即可在部署前自动处理后端JS文件中的console语句。
内容的提问来源于stack exchange,提问作者Zaeem
相关产品推荐
相关产品推荐

