react-app-rewired
和 customize-cra
对 webpack
进行配置定义主要是用的插件react-app-rewired customize-cra
安装yarn add react-app-rewired customize-cra -D
首先先在package.json
中配置 把react-scripts
替换成为react-app-rewired
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
替换成为
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
在项目根目录和package.json
同级下面新建一个 config-overrides.js
的文件
const { override } = require('customize-cra')
const path = require('path')
module.exports = {
webpack: override(
// 设置配置代码
)
}
React
使用@
操作符代表 src
目录-从customize-cra
导入addWebpackAlias
const {
...
addWebpackAlias,
...
} = require('customize-cra')
module.exports = {
webpack: override(
...
// 配置 @
addWebpackAlias({
'@': path.resolve(__dirname, 'src')
})
...
)
}
customize-cra
导入fixBabelImports
const {
...
fixBabelImports,
...
} = require('customize-cra')
module.exports = {
webpack: override(
...
// 配置antd 按需引入
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css'
}),
...
)
}
customize-cra
导入addWebpackResolve
例子 import Personal from './components/Personal.tsx'
—> import Personal from './components/Personal'
const {
...
addWebpackResolve,
...
} = require('customize-cra')
module.exports = {
webpack: override(
...
// 导入文件的时候可以不用添加文件的后缀名
addWebpackResolve({
extensions: ['.tsx', '.ts', '.js', '.jsx', '.json']
}),
...
)
}
const {
...
override,
overrideDevServer,
...
} = require('customize-cra')
module.exports = {
webpack: override(),
处理跨域
devServer: overrideDevServer(config => {
config.proxy = {
'/proxy/': {
target: 'http://127.0.0.1:7001/v1',
changeOrigin: true,
pathRewrite: { '^/proxy': '/' }
}
}
return config
})
}