1. 程式人生 > 其它 >react17修改全域性webpack配置並增加全域性less變數

react17修改全域性webpack配置並增加全域性less變數

配置步驟:

    • 引入react-app-rewired外掛
      react-app-rewired的作用就是在不eject的情況下,覆蓋create-react-app的配置
    • 安裝customize-cra
      npm install react-app-rewired customize-cra --save-dev
    • 安裝style-resources-loader
      npm install style-resources-loader
    • 修改 package.json 裡的啟動配置
    • npminstalllessless-loader--dev
/* package.json */
"scripts
": { - "start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test --env=jsdom", + "test": "react-app-rewired test --env=jsdom", }
  • 根目錄建立config-overrides.js 並配置修改
const { override
, addWebpackAlias, addLessLoader } = require('customize-cra') const path = require('path') // module.exports = function override(config, env) { // // do stuff with the webpack config... // return config; // }; module.exports = override( addLessLoader({ lessOptions: { javascriptEnabled: true, localIdentName:
'[local]--[hash:base64:5]' } }), //配置路徑別名 addWebpackAlias({ ['assets']: path.resolve(__dirname, './src/assets'), ['images']: path.resolve(__dirname, './src/assets/images'), ['libs']: path.resolve(__dirname, './src/libs'), ['components']: path.resolve(__dirname, './src/components'), }), (config) => { //修改、新增loader 配置 : // 所有的loaders規則是在config.module.rules(陣列)的第二項 // 即:config.module.rules[2].oneof (如果不是,具體可以列印 一下是第幾專案) // 修改 less 配置 ,規則 loader 在第8項( ***此處根據實際專案列印填寫,不一定是第7項*** ) const loaders = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf; // console.log(loaders[8]) loaders[8].use.push({ loader: 'style-resources-loader', options: { patterns: path.resolve(__dirname, './src/assets/css/variable.less')//全域性引入公共的scss 檔案 } }) return config } )
  • variable.less,需要新增全域性樣式變數,直接在這個檔案新增
  • @primary-color: #004080;
    @bg-gray-color: #F4F4F4;

若出現less問題,請注意less版本問題

我使用的是

"less": "^3.0.4",
    "less-loader": "^5.0.0",

參考

http://www.zyiz.net/tech/detail-145763.html

https://blog.csdn.net/zhengwenhaodezw/article/details/115327986

https://blog.csdn.net/weixin_44135121/article/details/109850564

https://blog.csdn.net/weixin_44245226/article/details/104470570