为提升项目测试效率,最近多个项目接入了项目效率工具icover,在这过程中也踩了一些坑,分享出来供其他有需求的同学参考。
接入icover主要做两步工作:
1,Modify babel config BABEL_ENV=test模式下使用@58fe/babel-plugin-icover babel插件
2,Add build pattern 给icover 设置 BABEL_ENV=test
但是由于各个项目的打包构建,babel使用方式,babel版本大同小异,在接入的过程中我们需要熟系babel的配置使用。
先来介绍一下babel的单独使用
babel单独使用有两种方式
1,使用配置文件,安装核心包
tip: babel.config.json (requires v7.8.0 and above)
babel.config.js if you are using an older Babel version
在实际的项目中类似如下所示皆为babel配置:
-
Project-wide configuration
-
-
babel.config.json files, with the different extensions (.js, .cjs, .mjs)
-
-
File-relative configuration
-
-
.babelrc.json files, with the different extensions (.babelrc, .js, .cjs, .mjs)
-
package.json files with a "babel" key
-
命令行对js文件进行compile, 例如:
./node_modules/.bin/babel src --out-dir lib
将src下的js按照config编译到lib目录
2,安装babel/cli
命令行对js文件进行compile同上
单独使用的场景较少,下面介绍一下babel集成其他工具使用
在webpack中集成babel:
1,安装核心包
npm install --save-dev babel-loader @babel/core
2,引入babel-loader
3, 抽取babel配置到配置文件
babel.config.js
module.exports = {
env: {
test: {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: [
["@58fe/babel-plugin-icover"],
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator",
[require("@babel/plugin-proposal-class-properties"), { loose: true }],
"@babel/plugin-transform-regenerator",
"@babel/plugin-transform-runtime",
],
},
production: {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator",
[require("@babel/plugin-proposal-class-properties"), { loose: true }],
"@babel/plugin-transform-regenerator",
"@babel/plugin-transform-runtime",
],
},
development: {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator",
[require("@babel/plugin-proposal-class-properties"), { loose: true }],
"@babel/plugin-transform-regenerator",
"@babel/plugin-transform-runtime",
],
},
},
};
webpack打包时会自动pick babel的config文件对对应的目录进行compile。
在vite中使用babel
vite将babel的配置集成到了对应的插件中
以
@vitejs/plugin-react为例 配置如下:
export default defineConfig({
plugins: [react({babel: {
presets: [...],
// Your plugins run before any built-in transform (eg: Fast Refresh)
plugins: [...],
// Use .babelrc files
babelrc: true,
// Use babel.config.js files
configFile: true,
}})]
})
知道了以上配置相关的知识,添加icover无非是看项目使用那种babel的使用方式,修改对应使用方式的环境,添加新的打包命令脚本即可。