初始化React应用
yarn create react-app my-app --template typescript
复制所有依赖文件和相应的依赖(webpack、babel等)到你的项目
cd my-app
yarn eject
Note: this is a one-way operation. Once you eject
, you can’t go back!
添加less、less-loader依赖
yarn add less@3.12.2 less-loader@6.2.0
修改webpack.config.js配置文件,添加less-loader配置4
在红框选中代码后面追加下面的代码
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
在红框选中代码后面追加下面的代码
// Opt-in support for Less (using .less extensions).
// By default we support Less Modules with the
// extensions .module.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,
},
// Adds support for CSS Modules, but using LESS
// using the extension .module.less
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'less-loader'
),
},
修改package.json文件,添加less忽略规则
修改react-app-env.d.ts文件,添加module定义配置
在红框选中代码后面追加下面的代码
declare module '*.module.less' {
const classes: { readonly [key: string]: string };
export default classes;
}
将项目src目录下面的css文件修改为less文件
结束
重新运行项目,引入less,发现是不是可以使用了