preface

How to configure @path in react project? There are too many files./ It is not easy to find the path of the file

Step 1.

  1. Created in the project root directoryjsconfig.jsonThe configuration file
  2. Add the following configuration to the configuration file

Jsconfig. Json in:

{
  "compilerOptions": {
    "baseUrl": ". /"."paths": {
      "@ / *": ["src/*"]}}}Copy the code

VSCode automatically reads the configuration in jsconfig.json to let VSCode know that @ is SRC

2. Use craco to configure the path alias

What is craco

Craco is a custom configuration tool for create-React-app. Configure the @ path alias so that the scaffold tool can recognize @

Create-react-app (CRA) hides all engineering configurations in the react-scripts package, so no configuration information or configuration files are seen in the project.

If you want to change the default CRA configuration, there are several options:

  1. 【 recommended 】 Use third-party libraries to modify, for example,@craco/craco
  2. By performingyarn ejectCommand, releasereact-scriptsTo the project (note: this operation is irreversible!!)

Procedure for using crACO

  1. The installation package. npm i -D @craco/craco

  2. In the project root directory, create the configuration file: craco.config.js. Custom changes can be made in the configuration file.

    craco.config.js

    Configuring a Path Alias

const path = require('path')
module.exports = {
  webpack: {
    alias: {
      The '@': path.join(__dirname, 'src')}}}Copy the code
  1. Modify thepackage.jsonScript commands in

Package. The json:

// Change the start, build, and test commands to craco mode

"scripts": {
  "start": "craco start"."build": "craco build"."test": "craco test"."eject": "react-scripts eject"
},
Copy the code
  1. In your code, you can pass@To represent the absolute path to the SRC directory
  2. Restart the project for the configuration to take effect

Call it a day