在新版本的react中分别添加sass與less支援,注意是用create-react-app腳手架工具建立的項目。
添加sass支援
添加sass支援非常簡單,隻需要執行以下指令安裝node-sass即可,如果不生效,請重新開機項目。
npm i node-sass --save
添加less支援
添加less支援稍微有點麻煩,因為對sass的支援在create-react-app腳手架中已經配置好了,但是less的沒有配置,需要我們手動配置,請按照以下步驟:
安裝less和less-loader
npm i less less-loader --save
釋放eject
npm run eject
此指令會在目前目錄下生産config檔案夾
修改配置檔案
打開/config/webpack.config.js檔案,找到以下代碼:
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
// **********
//**********
// **********
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
在以上代碼中,原來的代碼是沒有,隻是為了突出這個位置,可以看到已經配置好了sass,把*替換為以下代碼,然後重新開機即可。
// 添加less-loader
{
test: /\.less$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('less-loader') // compiles Less to CSS
}
],
},
以上。