前言
在使用qiankun微前端的时候,我们需要构建React微应用。在官方案例中使用了@rescripts/cli插件,这个插件由于版本不同,坑也是蛮多的。本文简单总结了rescripts配置支持装饰器语法的经验。
项目目录
如下:
image.png
用红框圈起来的就是关键的三个配置文件。
package.json文件
这个文件中主要是一些需要的依赖,主要包括两部分:
- 一是babel相关,版本很重要,6和7的配置是不一样的,我这里用的7
"dependencies": {
"@babel/core": "7.9.0",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-proposal-decorators": "^7.8.3",
"@babel/preset-env": "^7.9.5",
"antd": "^3.25.2",
"axios": "^0.25.0",
"babel-eslint": "10.1.0",
"babel-jest": "^24.9.0",
"babel-loader": "8.1.0",
"babel-plugin-named-asset-import": "^0.3.6",
"babel-preset-react-app": "^9.1.2",
}
- 二是rescripts相关,rescripts这几个依赖很奇葩,互相有依赖关系,版本最好不要变
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.16.7",
"@rescripts/cli": "^0.0.14",
"@rescripts/rescript-env": "0.0.10",
"@rescripts/rescript-use-babel-config": "0.0.12",
"@rescripts/rescript-use-eslint-config": "0.0.11",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"react-scripts": "^3.4.1"
}
.babelrc文件
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": 3
}
],
"react-app"
],
"plugins": [
// ["import", {
// "libraryName": "antd",
// "libraryDirectory": "es",
// "style": "css" // `style: true` 会加载 less 文件
// }],
// ↓这里支持装饰器语法配置
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
.rescriptsrc.js
const { name } = require('./package');
const logConfig = {
webpack: config => {
config.output.library = `${name}-[name]`;
config.output.libraryTarget = 'umd';
config.output.jsonpFunction = `webpackJsonp_${name}`;
config.output.globalObject = 'window';
return config;
},
devServer: _ => {
const config = _;
config.headers = {
'Access-Control-Allow-Origin': '*',
};
config.historyApiFallback = true;
config.hot = false;
config.watchContentBase = false;
config.liveReload = false;
return config;
},
};
logConfig.isMiddleware = true
module.exports = [
// 这样才能使.babelrc文件生效
['use-babel-config', '.babelrc'],
logConfig,
]
后记
这就是本次踩坑后的总结,更多内容参考rescripts (worldlink.com.cn)