安装
npm install react-app-rewired customize-cra babel-plugin-import -D
改写package.json 的启动命令
原来的:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
修改后的:
"scripts": {
"start": "env-cmd -e dev react-app-rewired start",
"build:prod": "env-cmd -e prod react-app-rewired build",
"build:qa": "react-app-rewired build",
"test": "react-app-rewired test"
},
项目的根目录会多一个配置文件config-overrides.js (如果没有,手动新建)
const {
override,
fixBabelImports,
addLessLoader,
addWebpackAlias
} = require('customize-cra');
const path = require('path');
//webpack-plugin 插件修改
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const myPlugin = [
new UglifyJsPlugin({
uglifyOptions: {
warnings: false,
compress: {
drop_debugger: true,
drop_console: true
}
}
})
]
module.exports = override(
//按需加载
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
// style 的选项 ‘css' 表示引入的css文件 true 表示引入的less
style: true,
}),
// 这里设置less
addLessLoader({
javascriptEnabled: true,
modifyVars: {
'@primary-color': '#d214a2',
'@font-size-base': '12px',
}
}),
//webpack 路径的解析
addWebpackAlias({
'@': path.resolve(__dirname, "src")
}),
//暴露webpack的配置 config 是webpack里面对应的config ,evn环境变量
(config, env) => {
loaders[5].use.push({
loader: 'sass-resources-loader',
options: {
resources: path.resolve(__dirname, 'src/asset/base.scss') //全局引入公共的scss 文件
}
})
}
);
env-cmd 环境变量配置
安装
yarn add env-cmd -D
根目录 新增 .env-cmdrc.json 文件
{
"dev": {
"PORT": 5055,
"REACT_APP_API_URL": "/manage",
"REACT_APP_RETRY": 4,
"REACT_APP_MD5_SUFFIX": "dmx.top.com.&dmX.%.X%m#d"
},
"prod": {
"REACT_APP_API_URL": "http://admin.lhyzn.com",
"REACT_APP_RETRY": 10,
"REACT_APP_MD5_SUFFIX": "dmx.top.com.&dmX.%.X%m#d"
}
}
http-proxy-middleware 网络请求跨域配置
安装
yarn add http-proxy-middleware
src目录下新建setupProxy.js
/*
* 代理 跨域
* */
const {createProxyMiddleware} = require('http-proxy-middleware');
// app 这个app 代表的是服务器 是webpack-dev-server 底层用express实现的
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5055',
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
})
);
app.use(
'/manage',
createProxyMiddleware({
target: 'http://admin.lhyzn.com',
changeOrigin: true,
pathRewrite: {
"^/manage": ""
}
})
);
};
|
请发表评论