使用 create-react-app 腳手架創建項目后,默認是不支持 less 的。所以我們需要手動添加。
第一步 暴露webpack配置文件
使用 create-react-app 創建的項目,默認情況下是看不到 webpack 相關的配置文件,我們需要給它暴露出來,使用下面命令即可
yarn eject
運行之后,我們發現多了一個config文件夾,
這樣就可以修改 webpack 相關配置了。
第二步 添加less 在項目根目錄 使用 npm 或者 yarn 來安裝antd less 和 less-loader
-
yarn add babel-plugin-import
-
yarn add antd
-
yarn add less less-loader
第三步 修改package.json:添加antd庫的樣式
"babel": { "presets": [ "react-app" ], "plugins": [ [ "import", { "libraryName": "antd", "style": "css" } ] ] }
第四步 復制代碼修改配置環境(webpack.config.js) 定義全局變量
// style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/;
第五步 復制代碼配置less-loader
//在大概466行會看到如下代碼 { test: sassModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent, }, 'sass-loader' ), }, //在此代碼后添加如下代碼 { test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2 }, 'less-loader' ), }, { test: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, modules: true, getLocalIdent: getCSSModuleLocalIdent, }, 'less-loader' ), },
第六步 復制代碼定義全局樣式
//注釋掉大概114行 // if (preProcessor) { // loaders.push({ // loader: require.resolve(preProcessor), // options: { // sourceMap: isEnvProduction && shouldUseSourceMap, // }, // }); // } // return loaders; //替換為如下 if (preProcessor) { let loader = require.resolve(preProcessor) if (preProcessor === "less-loader") { loader = { loader, options: { modifyVars: { //自定義主題 'primary-color': ' #1890ff ', }, javascriptEnabled: true, } } } loaders.push(loader); } return loaders;
第七步 復制代碼修改package.json
"babel": { "presets": [ "react-app" ], "plugins": [ [ "import", { "libraryName": "antd", "style": true //修改處 } ] ] }
