在`create-react-app`中使用`webpack-stylesheet-variable-replacer-plugin`

create-react-app中使用webpack-stylesheet-variable-replacer-plugin

第一步:引入react-app-rewired

create-react-app中無(wú)法直接修改webpack配置,所以需要引入react-app-rewired來(lái)實(shí)現(xiàn)覆蓋webpack配置(也有其他方案,此處只演示使用react-app-rewired的方式)

1、下載包 : npm install react-app-rewired --save-dev

2、 在根目錄中創(chuàng)建文件: config-overrides.js;

3、 將以下文件貼入 config-overrides.js

module.exports = function override(config, env) {
  //do stuff with the webpack config...
  return config;
}

4、 修改package.json文件:

  /* 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",
+   "test": "react-app-rewired test",
    "eject": "react-scripts eject"
}

最終效果如下:

{
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }

第二步:配置webpack-stylesheet-variable-replacer-plugin

1、安裝包 :npm i webpack-stylesheet-variable-replacer-plugin -D

2、在 config-overrides.js中引入包:

const WebpackVariableReplacer = require('webpack-stylesheet-variable-replacer-plugin'); 

3、 在override方法中加入webpackVariableReplacer配置

module.exports = function override(config, env) {
  //do stuff with the webpack config...
  config.plugins.push(new WebpackVariableReplacer({
    htmlFileName: 'index.html', // if your application has a html file , It's used for inject javascript file.
    publicPath: config.output.publicPath, // as you need to inject javascript file , this is path prefix for visite the file for replace variable.
    matchVariables: { // It's a key-value Object , key is only alias for your variable , such as I use 'main' for main color I use in application.
      // notice that value is the original value in your style, not target you want to replace.
      main: '#282c34',
    }
  }));
  return config;
}

第三步 界面中加入換膚代碼

<button onClick={()=> window.replaceStyleVariable({main: getRandomColor()})}>replace random color</button>
function getRandomColor() {
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length === 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

第四步 開始愉快的玩耍吧,沒(méi)有更多了。

demo鏈接:https://github.com/eaTong/webpack-stylesheet-variable-replacer-plugin/tree/master/demo/create-react-app-demo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容