Create-React-APP + Antd + less Module配置

CRA版本為3.0.1。
eject出來之后只有一個(gè)webpack.config.js。不再區(qū)分為dev和prod兩個(gè)配置文件。

首先安裝 antd,less,less-loader

npm install antd
npm install less less-loader

eject CRA新建的項(xiàng)目

config目錄下的文件如下:


image.png

修改webpack.config.js

首先配置less module

在cssRegex和sassRegex附近(line 42左右)添加如下代碼

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

再找到使用cssRegex的代碼位置(line 460左右)添加如下代碼

{
             test: lessRegex,
             // exclude: lessModuleRegex,
             exclude: /node_modules/,
             use: getStyleLoaders(
               {
                 modules: true,
                 importLoaders: 3,
                 // javascriptEnabled: true,
                 sourceMap: isEnvProduction
                   ? shouldUseSourceMap
                   : isEnvDevelopment
               },
               "less-loader"
             ),
             // Don't consider CSS imports dead code even if the
             // containing package claims to have no side effects.
             // Remove this when webpack adds a warning or an error for this.
             // See https://github.com/webpack/webpack/issues/6571
             sideEffects: true
           },
           {
             test: lessRegex,
             // exclude: lessModuleRegex,
             include: /node_modules/,
             use: getStyleLoaders(
               {
                 importLoaders: 3,
                 // javascriptEnabled: true,
                 sourceMap: isEnvProduction
                   ? shouldUseSourceMap
                   : isEnvDevelopment
               },
               "less-loader"
             ),
           },
           
           // Adds support for CSS Modules, but using SASS
           // using the extension .module.scss or .module.sass
           {
             test: lessModuleRegex,
             use: getStyleLoaders(
               {
                 importLoaders: 3,
                 sourceMap: isEnvProduction
                   ? shouldUseSourceMap
                   : isEnvDevelopment,
                 modules: true,
                 getLocalIdent: getCSSModuleLocalIdent
               },
               "less-loader"
             )
           },

注意上面的less-loader配置了2次,第一次主要是為了exclude antd。從而可以正確加載antd的樣式。

修改getStyleLoaders方法

當(dāng)前版本CRA生成的webpack.config.js文件加載css loader等都是通過getStyleLoaders方法(line74左右)實(shí)現(xiàn)的。但這個(gè)方法有點(diǎn)小問題,像上面那樣配置了第二個(gè)參數(shù)“l(fā)ess-loader”,并沒有被該方法使用。所以如下修改改方法

const getStyleLoaders = (cssOptions, preProcessor) => {
    const loaders = [
      isEnvDevelopment && require.resolve('style-loader'),
      isEnvProduction && {
        loader: MiniCssExtractPlugin.loader,
        options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
      },
      {
        loader: require.resolve('css-loader'),
        options: cssOptions,
      },
      {
        // Options for PostCSS as we reference these options twice
        // Adds vendor prefixing based on your specified browser support in
        // package.json
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebook/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            require('postcss-preset-env')({
              autoprefixer: {
                flexbox: 'no-2009',
              },
              stage: 3,
            }),
            // Adds PostCSS Normalize as the reset css with default options,
            // so that it honors browserslist config in package.json
            // which in turn let's users customize the target behavior as per their needs.
            postcssNormalize(),
          ],
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
      },
    ].filter(Boolean);
    if (preProcessor) {
      loaders.push({
        loader: require.resolve(preProcessor),
        options: {
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modifyVars: { '@primary-color': '#2577E0' },
          javascriptEnabled: true,
        },
      });
    }
    return loaders;
  };

增加了最后的if (preprocessor)的判斷,觸發(fā)less-loader及antd修改主題的相關(guān)配置。
到這里webpack的相關(guān)配置修改就完成了。
最后:

Antd的按需加載

npm install babel-plugin-import

先安裝babel插件
然后在項(xiàng)目的根目錄下(就是和package.json相同的層級(jí))新建文件babel.config.js,里面的內(nèi)容如下

module.exports = {
  plugins: [
    ["import", { libraryName: "antd", style: true}] // `style: true` 會(huì)加載 less 文件
  ]
};

以上,Create-React-App新建項(xiàng)目,引入antd及按需加載,使用less作為業(yè)務(wù)代碼的樣式文件,并實(shí)現(xiàn)css模塊化配置完成。

2019-8

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容