一、Sass
react-scripts@2.0.0 以上版本才适用。
react-scripts主要设计原理是将配置好的如 Webpack,Babel,ESLint
,合并到 react-scripts
这npm包中,用户就可以开箱即用。很多开发者都在这基础上进行改造开发。注意 react-scripts
就是create-react-app脚手架的核心配置代码。
1-1 安装依赖
要使用Sass必须首先安装 `node-sass`
$ npm install node-sass --save
$ # or
$ yarn add node-sass
安装完之后,我们就可以直接把原来的CSS文件后缀直接改为 .scss
或者.sass
,然后组件中导入的文件不再是 css文件而给我scss文件即可。
import React, {Component} from 'react';
import store from './Store/Index';
import {AddNumCreator, MinusNumCreator} from './Store/ActionCreaters';
import './App.scss';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1>潇洒</h1>
</header>
</div>
);
}
}
export default App;
1-2 在sass文件中引入其他sass文件
~ 就代表: node_modules
@import 'styles/colors.scss'; //这边路径以当前文件路径为参照
@import '~bootstrap/dist/css/bootstrap.css';
二、Less
由于 create-react-app 脚手架中并没有配置关于 less 文件的解析,所以我们需要自己进行配置。需要安装的插件 less , less-loader 。npm install less less-loader
#1.使用 yarn reject暴露配置文件
$ react-scripts eject
NOTE: Create React App 2 supports TypeScript, Sass, CSS Modules and more without ejecting: https://reactjs.org/blog/2018/10/01/create-react-app-v2.html
? Are you sure you want to eject? This action is permanent. (y/N) y
#2.修改config/webpack.config.js
//找到如下代码
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
//修改为如下代码
const cssRegex = /\.(css|less)$/;
const cssModuleRegex = /\.module\.(css|less)$/;
//找到这段代码
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// 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: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'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,
#3.添加@路径配置,修改config/webpack.config.js
// 找到alias 添加代码如下:
'@':path.join(__dirname, '..', "src")