Build a project using create-react-app scaffolding and introduce less into it
Pay attention to a small detail
Build a project using create-react-app scaffolding and introduce less into it
Reference resources Two Ways of Big Man Can be achieved, which encountered a pit, record it
After scaffolding, open the hidden configuration file
Command line input
npm run eject //perhaps yarn eject
A config folder will appear in the current directory
Install less and less-loader
npm install less less-loader --save
Configure webpack.config.js
Find the webpack.config.js file under the config folder
The first way
Add less configuration variable
const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; const lessRegex = /\.less$/; // New less configuration const lessModuleRegex = /\.module\.less$/; // Add less configuration, which is not actually configurable.
Increase rule rules under module
You can copy the configuration of cssRegex or sassRegex.
{ test: sassModuleRegex, use: getStyleLoaders({ importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent }, "sass-loader" ) }, { test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders({ importLoaders: 1,// Value 1 modules: true, // Adding this allows access to css in a modular way sourceMap: isEnvProduction && shouldUseSourceMap }, "less-loader" ), sideEffects: true }, // It doesn't matter if the test is deleted. { test: lessModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent }, "less-loader" ) }, // "file" loader makes sure those assets get served by WebpackDevServer.
A few points need to be noted:
1. The value of importLoaders in Less Regex is 1
2. Adding modules configuration to Less Regex's use
If you need to call through modules, you need to set modules to true, and you can use them through styles.title. Import styles from'. / index. less', using < div className = {styles.title} > </div >
The second configuration
You can include less in the configuration of css without adding new variables
const cssRegex = /\.(css|less)$/; //Increase less const cssModuleRegex = /\.module\.(css|less)$/; { test: cssRegex, exclude: cssModuleRegex, use: getStyleLoaders({ importLoaders: 2,// Change to 2 modules: true,//Using Modular Access Style sourceMap: isEnvProduction && shouldUseSourceMap }, "less-loader" //Add 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 }
Both approaches can be successful.
Pay attention to a small detail
Introduce less file in js file, remember to add suffix
for example
import "./App.less";