首先創建一個react項目,使用新的方式 npx
npx create-react-app my-app
網上有很多方法去擴展react的webpack,比較常見的做法是運行 yarn eject 將所有的react配置暴露出來。但是這樣就會使得項目變得臃腫,看起來代碼多了很多。這里不做介紹。
今天介紹另外一種擴展webpack的方式 customize-cra
一、首先是安裝依賴
yarn add -D customize-cra react-app-rewired
二、修改 package.json 的 scripts 配置
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test --env=jsdom", "eject": "react-scripts eject" }
四、在項目的更目錄下創建 config-overrides.js
const { override } = require('customize-cra');
module.exports = {};
五、添加一些常用的配置項
目前所配置的有: 跨域設置,px 轉 rem,ant-design-mobile 按需加載,打包壓縮css 和 js,快捷路徑
// 安裝compression-webpack-plugin 壓縮js為gzip yarn add compression-webpack-plugin -D // 安裝 lib-flexible 設置跟元素的font-size yarn add lib-flexible -D // 安裝 babel-plugin-import 按需引入ant yarn add babel-plugin-import -D
下面是一些 config-overrides.js 的配置
const path = require('path'); const { override, fixBabelImports, addWebpackAlias, overrideDevServer, addPostcssPlugins } = require('customize-cra'); // show https://github.com/arackaf/customize-cra const CompressionWebpackPlugin = require('compression-webpack-plugin'); function resolve(dir) { return path.join(__dirname, '.', dir) } const addCustomize = () => config => { if (process.env.NODE_ENV === 'production') { // 關閉sourceMap config.devtool = false; // 配置打包后的文件位置 // config.output.path = resolve('dist'); // config.output.publicPath = './'; // 添加js打包gzip配置 config.plugins.push( new CompressionWebpackPlugin({ test: /\.js$|\.css$/, threshold: 1024, }), ) } return config; } const devServerConfig = () => config => { return { ...config, proxy: { '/api': { target: 'xxx', changeOrigin: true, pathRewrite: { '^/api': '/api', }, } } } } module.exports = { webpack: override( // 配置antd 的按需引入 fixBabelImports('import', { libraryName: 'antd-mobile', style: 'css' }), // 配置路徑訪問快捷鍵 @/xxx addWebpackAlias({ '@': resolve('src'), }), // postCss 自動將px轉為rem 需要配合 lib-flexible 使用 addPostcssPlugins([ require('postcss-pxtorem')({ rootValue: 75, propList: ['*'], minPixelValue: 2, selectorBlackList: ['am-'] }) ]), // 壓縮js等 addCustomize() ), // 本地啟動配置,可以設置代理 devServer: overrideDevServer( devServerConfig() ) };
參考: