cra: addlessloader 配置报错解决方案(create-react-app)

报错1:Less Loader

Less Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'localIdentName'. These properties are valid: object { lessOptions?, additionalData?, sourceMap?, webpackImporter?, implementation? }
解决方法其实在报错问题上有,外层配置加一层lessOptions,如下

addLessLoader({
    lessOptions: {
      javascriptEnabled: true,
      localIdentName: '[local]--[hash:base64:5]',
    },
  }),

报错2:PostCSS Loader

PostCSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'plugins'. These properties are valid:
github搜到的解决方案,亲测有效,增加如下配置

adjustStyleLoaders(({ use: [, , postcss] }) => {
    const postcssOptions = postcss.options;
    postcss.options = { postcssOptions };
  }),

完整版

npm install react-app-rewired customize-cra babel-plugin-import -D

根目录:config-overrides.js

const {
  override,
  fixBabelImports,
  addWebpackAlias,
  addLessLoader,
  adjustStyleLoaders,
  addWebpackModuleRule,
  addPostcssPlugins
} = require('customize-cra');
const path = require('path');
const { name } = require('./package.json');
const paths = require('react-scripts/config/paths');
paths.appBuild = path.join(path.dirname(paths.appBuild), name);

module.exports = override(
  (config) => ({
    ...config,
    devtool: config.mode === 'development' ? 'cheap-module-source-map' : false,
  }),
  fixBabelImports('import', {
    libraryName: 'antd',
    style: 'css',
  }),
  addWebpackAlias({
    '@': path.resolve(__dirname, './src'),
  }),
  addLessLoader({
    lessOptions: {
      javascriptEnabled: true,
      localIdentName: '[local]--[hash:base64:5]',
    },
  }),
  adjustStyleLoaders(({ use: [, , postcss] }) => {
    const postcssOptions = postcss.options;
    postcss.options = { postcssOptions };
  }),
  addWebpackModuleRule({
    test: /\.(png|jpg|gif|jpeg|svg)$/i,
    use: [{
      loader: 'url-loader',
      options: {
        limit: 20 * 1024,
        esModule: false,
        outputPath: `static/imgs/`,
      },
    },],
  }),
);

package.json

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },

你可能感兴趣的:(前端框架--react,前端实用知识点整理,postcss,前端,javascript,less)