React在crate- react- app中使用less文件
创建启动项目
yarn start
修改App.jsx/App.js文件内容
/* App.jsx */
// import './App.css';
import './App.less'
function App() {
return (
<div className="App">
<div className="demo">
这是一个项目
</div>
</div>
);
}
export default App;
安装 craco 并修改 package.json 里的 scripts 属性。
yarn add @craco/craco
/* package.json */
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}
安装 craco-less 并创建或修改 craco.config.js
yarn add craco-less
craco.config.js文件创建在根目录
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
],
};
less文件编辑后运行
less文件随便写点东西,然后引用运行
/* Less */
@color: #999;
@bgColor: skyblue;//不要添加引号
@width: 50%;
.demo{
color: @color;
background-color: @bgColor;
width: @width;
height: 50px;
margin: 0 auto;
text-align: center;
}
搜了很多博主的文章发现大多数都是需要暴露webpack配置,那种方法我没试过,但是我觉得很麻烦。
注意eject命令是一次性命令,运行后无法恢复
npm run eject
这时项目结构就会多出了一个config文件,以及package.json 文件中多了很多内容