1.新建React项目,根据需要是否选用typescript
npx create-react-app demo --template typescript
2.使用less
1.暴露webpack配置
yarn eject
2.修改webpack.config.js文件,在合适的位置添加以下代码
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
module.exports = function (webpackEnv) {
return {
module: {
rules: [
{
oneOf:[
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
},
"less-loader"
),
sideEffects: true,
},
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
"less-loader"
),
},
]
}
]
}
}
}
3.重新启动,测试less是否生效
疑难杂症1——报错
TypeError: this.getOptions is not a function原因:less-laoder安装版本太高,于是从原来的10.*.*版本换成了5.0.0...
疑难杂症2——引入less文件的地方报错
Cannot find module './App.less'原因:在typscript中是无法识别非代码资源,需要主动的去声明这个module。项目编译过程中会自动去读取.d.ts这种类型的文件,所以不需要我们手动地加载他们。当然.d.ts文件也不能随便放置在项目中,这类文件和ts文件一样需要被typescript编译,所以一样只能放置在tsconfig.json中include属性所配置的文件夹下。
在src下新建global.d.ts文件:
declare module '*.less'
3. 引入Antd
yarn add antd
yarn add -D babel-plugin-import
修改 src/App.less,在文件顶部引入 antd/dist/antd.css:
@import '~antd/dist/antd.css';
发现antd样式不生效,解决办法1:该用在App.tsx文件里引入antd的样式文件:
import 'antd/dist/antd.css'
如果还是生效,可能是因为下载的antd文件它是在我们的node_modules文件夹下,在antd(node_modules)目录下不开启局部css样式,在非antd(非node_modules)目录下开启局部css样式。
4. 文件夹取别名,用绝对路径取代相对路径
const path = require('path')
module.exports = {
resolve: {
// 表示这几个文件的后缀名可以省略不写,默认是js、json
extensions: ['.js', '.jsx', '.json'],
alias: { // 别名
'@': path.join(__dirname, './src')
}
}
}
5. 将svg图标用做React组件
参考文章:
How to use SVG Icons as React Components
How to pass props to components in React