antd按需加载遇到的坑:.bezierEasingMixin();

时间:2024-05-21 20:35:13

在less升级到3.x, webpack 升级到4.x的时候,按需加载就会出现错误 了。

./node_modules/antd/lib/button/style/index.less (./node_modules/css-loader??ref--6-oneOf-7-1!./node_modules/postcss-loader/src??postcss!./node_modules/less-loader/dist/cjs.js!./node_modules/antd/lib/button/style/index.less)
// https://github.com/ant-design/ant-motion/issues/44
.bezierEasingMixin();
^
Inline JavaScript is not enabled. Is it set in your options?
      in /myproject/react/antedemo/node_modules/antd/lib/style/color/bezierEasing.less (line 110, column 0)

Inline JavaScript is not enabled 这句话是关键。。

找到issue后,开始解决问题

找到的比较靠谱的答案如下:

antd按需加载遇到的坑:.bezierEasingMixin();

也就是给options添加如下代码:

{
  loader: "less-loader",
  options: {
    javascriptEnabled: true
  }
}

但是尴尬的时候,webpack4的配置已经全部变化了。
loader被封装了一个函数。

配置如下:

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
{
            test: lessRegex,
            exclude: lessModuleRegex,
            use: getStyleLoaders({
              importLoaders: 3,
              modifyVars: {
                'primary-color': "#f9c700"
              },
              javascriptEnabled: true,
            }, 'less-loader'),
          },
          // Adds support for CSS Modules, but using SASS
          // using the extension .module.scss or .module.sass
          {
            test: lessModuleRegex,
            use: getStyleLoaders(
              {
                importLoaders: 3,
                modules: true,
                getLocalIdent: getCSSModuleLocalIdent,
              },
              'less-loader'
            ),
          },

关键点来了:

const getStyleLoaders = (cssOptions, preProcessor) => {
  const loaders = [
    ///其他代码
  if (preProcessor) {
    loaders.push(
      {
        loader: require.resolve(preProcessor),
        options: cssOptions,
      }
    );
  }
  return loaders;
};

到这里完美解决了