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.
- Created in the project root directory
jsconfig.json
The configuration file - 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:
- 【 recommended 】 Use third-party libraries to modify, for example,
@craco/craco
- By performing
yarn eject
Command, releasereact-scripts
To the project (note: this operation is irreversible!!)
Procedure for using crACO
-
The installation package. npm i -D @craco/craco
-
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
- Modify the
package.json
Script 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
- In your code, you can pass
@
To represent the absolute path to the SRC directory - Restart the project for the configuration to take effect
Call it a day