如何将React-app-rewired与Customize-CRA集成

Kar*_*oko 3 web-config reactjs webpack

我想通过react-app-rewired覆盖Webpack配置。但是我在项目中使用Ant设计,因此必须使用Customize-CRA导入Babel插件等。如何将React-app-rewired和Customize-CRA一起使用。

React-app-rewire的config-overrides.js如下所示:

module.exports = function override(config, env) {
  config.module.rules = config.module.rules.map(rule => {
        if (rule.oneOf instanceof Array) {
            return {
                ...rule,
                oneOf: [
                    {
                        test: /\.(svg|png|jpg|jpeg|gif|bmp|tiff)$/i,
                        use: [
                            {
                                loader: 'file-loader',
                                options: {
                                    name: '[path][name]-[hash:8].[ext]'
                                }
                            }
                        ]
                    },
                    ...rule.oneOf
                ]
            };
        }

        return rule;
    });

  return config;
}
Run Code Online (Sandbox Code Playgroud)

Customize-CRA的config-overrides.js如下:

const {override, fixBabelImports, addLessLoader, addDecoratorsLegacy, disableEsLint} = require('customize-cra');

module.exports = override(
  addDecoratorsLegacy(),
  disableEsLint(),
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {'@primary-color': '#a50052'},
  }),
);

Run Code Online (Sandbox Code Playgroud)

谢谢。

小智 6

我想我遇到了您遇到的相同问题。Customize-cra覆盖将任意数量的覆盖函数作为参数。每个函数都以config作为其第一个参数。将其视为一个组合功能。进行现有的覆盖导出,将其放入您定义的函数中(我称为myOverrides或其他名称),然后使用您的覆盖函数作为参数之一导出custom-cra的覆盖。

之前:

module.exports = function override(config, env){
  // do stuff to config
  return config
}
Run Code Online (Sandbox Code Playgroud)

后:

function myOverrides(config) {
  // do stuff to config
  return config
}

module.exports = override(
  myOverrides,
  addDecoratorsLegacy(),
  disableEsLint(),
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {'@primary-color': '#a50052'},
  }),
);
Run Code Online (Sandbox Code Playgroud)


Ana*_*sia 0

在customize-cra为我工作之后放置react-app-rewired配置。如果我将一个对象分配给配置,它就不起作用,但如果我逐行修复配置,它就可以工作。我确信有一个更优雅的解决方案。

module.exports = function override(config, env) {
    const APP = process.env.REACT_APP_APP
    const BRAND = process.env.REACT_APP_BRAND

    addWebpackAlias({
        ['@app-config']: path.resolve(__dirname, `./src/brands/${BRAND}/app`),
    })

    config.entry = `./src/${APP}/index.js`
    config.resolve.alias['@app-config'] = path.resolve(__dirname, `./src/brands/${BRAND}`)
    config.resolve.modules = [
        path.join(__dirname, `src/brands/${BRAND}`)
    ].concat(config.resolve.modules)


    return config
};
Run Code Online (Sandbox Code Playgroud)