- create-react-app demo
- npm run eject
- npm i less less-loader –save
- npm i less-watch-compiler –save-dev
-
在 package.json 中添加
"scripts":{ "build-css": "less-watch-compiler --run-once --main-file=index.less src/less src/css", "watch-css": "npm run build-css && less-watch-compiler --main-file=index.less src/less src/css" }
- 运行 npm run watch-css
-
在 config 中的 webpack.config.js 中配置
// 修改前 {loader: require.resolve('css-loader'), options: options }, // 修改后 {loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: "[name]__[local]___[hash:base64:5]" // 更改 css modules 生成方法 }, }, // 修改 webpack 配置 less 部分,按照 sass 相同配置 const lessRegex = /\.less$/ const lessModuleRegex = /\.module\.less$/ oneOf:[ ..., { test: lessRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }, 'less-loader' ) }, { test: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: true, getLocalIdent: getCSSModuleLocalIdent }, 'less-loader' ), sideEffects: true }, ]
8. 删除原有依赖 重新安装依赖,然后 npm start 运行即可