1. The introduction

Create-react-app encapsulates the webpack configuration and hides the configuration file by default. How do I expose the configuration file to modify it? There are two ways:

  • npm run eject
  • react-app-rewired

2. npm run eject

The webpack configuration file, webpack.base.conf.js, is hidden under react-scripts in node_modules. You can run the following command to expose the webpack configuration file: NPM run eject

  • ejectIf is an unrecoverable operation, enter yeject.
  • ejectAfter that, you will find several new directories under the directoryThe config, script.

There are two webpack.config files, one for dev and one for PROd (the NPM run build configuration file). Paths are various paths. We can add our own paths to this file.

This exposes the disadvantages of configuration portals:

  • npm run ejectThe name is irreversible and cannot be hidden once the configuration file is exposed
  • Extended configuration andcreate-react-appThe built-inwebpackThe configurations are mixed together, which is not conducive to troubleshooting if configuration problems occur

Use 3.react-app-rewiredTo configure

react-app-rewired

The installation

NPM install [email protected] - save - dev

Create a file

Create config-overrides. Js file in the project root directory to modify the default configuration:

/* config-overrides.js */

module.exports = function override(config, env) {
  //do stuff with the webpack config...
  return config;
}
Copy the code

Modify thepackage.jsonStartup configuration in

Default configuration:

Read as follows:

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test"
  },
Copy the code

4. Configure the import path

The path alias can be configured to avoid ‘./.. /.. /’?

  1. inwebpack.config.jsaddaliasCan be configured according to the project:
resolve: { alias: { '@': path.resolve(__dirname, '.. /src') } },Copy the code

import { Banner } from ‘.. /.. /.. /src/components/Banner’; Import {Banner} from ‘@/components/Banner’;

  1. If ESlint checking is enabled, an error will be reported as follows:

Eslint-import-resolver-alias install: NPM install eslint-plugin-import eslint-import-resolver-alias –save-dev

Configuration. Eslintrc. Js:

"settings": {
  'import/resolver': {
    alias: {
      map: [
        ['@', path.resolve(__dirname, './src')]
      ],
      extensions: ['.js', '.less', '.jsx']
    }
  }
},
Copy the code

Refer to the article

  • Extend create-React-app webpack configuration