使用create-react-app构建react项目之后,配置less-loader,配置完了后,正常引入less没问题,但是@import "~antd/dist/antd.less"还是会报错:
Failed to compile.
./node_modules/antd/lib/style/index.less (./node_modules/css-loader??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/less-loader/dist/cjs.js!./node_modules/antd/lib/style/index.less)
// https://github.com/ant-design/ant-motion/issues/44
.bezierEasingMixin();
^
Inline JavaScript is not enabled. Is it set in your options?
// less
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders({
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
}, 'less-loader')
},
网上也能搜到,很多都是这么解决的,但是到我这里却出问题了???然后我就开始研究antd官网写法:
// webpack.config.js
module.exports = {
rules: [{
test: /\.less$/,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader', // translates CSS into CommonJS
}, {
loader: 'less-loader', // compiles Less to CSS
+ options: {
+ modifyVars: {
+ 'primary-color': '#1DA57A',
+ 'link-color': '#1DA57A',
+ 'border-radius-base': '2px',
+ // or
+ 'hack': `true; @import "your-less-file-path.less";`, // Override with less file
+ },
+ javascriptEnabled: true,
+ },
}],
// ...other rules
}],
// ...other config
}
对比我的代码和官网的代码,我发现官网还是原始的写法,并且还加上了一些配置,可以自定义主题,这似乎不错,于是我按照他的来改造。
首先我仔细看了下webpack.config.js里的getStyleLoaders函数,它的返回值是一个loader数组,正好可以作为use的值,它能接收两个参数:一个是cssOptions,接受对象、一个是preProcessor,并且只接受字符串。那么我的这里要传入less-loader以及对应的参数,字符串肯定是不够的,至少要传入对象才行,直接传肯定不行,那么怎么办呢?我想到了js的展开运算符,接下来是完整解决方案。
在webpack.config.js中:
// 大约第50行
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
// 大约第460行
// less
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders({
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
}, 'less-loader')
},
// .module.less
{
test: lessModuleRegex,
use: [
...getStyleLoaders({
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
{
loader: 'less-loader',
options: {
modifyVars: {
'primary-color': '#1DA57A'
},
javascriptEnabled: true
}
}
]
},
然后再在 getCSSModuleLocalIdent.js里边加上less:
到这里就解决了,最后再附上按需加载antd 的配置:
首先, npm i babel-plugin-import -D 或者 yarn add babel-plugin-import --dev
然后,继续在webpack.config.js里配置:
// 大约第366行
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'@svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
// import 按需加载
[
"import",
{
libraryName: 'antd',
libraryDirectory: 'es',
style: true
}
]
],
祝看到这篇文章的同学们技术有成!