Tags: React, 踩坑
日期: 2021/01/22css
使用create-react-app腳手架搭建的react項目,會自帶css和sass,可是沒有less,若是在項目中須要使用less,須要進行下載並進行一些配置。react
首先須要暴露Webpack配置文件,使用命令npm run eject
命令釋放,找到webpack.config.js文件webpack
搜索Sass
找到以下代碼git
// style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/;
在下面添加github
// 添加 less 解析規則 const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/;
而後找到以下配置web
// Adds support for CSS Modules (https://github.com/css-modules/css-modules) // using the extension .module.css { test: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { getLocalIdent: getCSSModuleLocalIdent, }, }), }, // Opt-in support for SASS (using .scss or .sass extensions). // By default we support SASS Modules with the // extensions .module.scss or .module.sass { test: sassRegex, exclude: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }, 'sass-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, }, // Adds support for CSS Modules, but using SASS // using the extension .module.scss or .module.sass { test: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { getLocalIdent: getCSSModuleLocalIdent, }, }, 'sass-loader' ), },
直接把Sass的配置複製到下面,關鍵字替換爲Lessnpm
//less配置 能夠直接複製上面的sass配置以後改爲less就行 { test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders( { importLoaders: 3, 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: lessModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { getLocalIdent: getCSSModuleLocalIdent, }, }, 'less-loader' ), },
保存便可sass
而後使用命令app
yarn add less less-loader --save
最後把項目中的css文件更名爲less,重啓項目便可less