Configure path alias in React project

created at 11-14-2021 views: 1

1. Use craco library

download

npm i @craco/craco --save

craco's GitHub address

2. Create a file

Create a file named `craco.config.js` on the project root path, at the same level as package.json.

my-app
├── node_modules
├── craco.config.js
└── package.json

3. Modify the package.json file

/* package.json */

"scripts": {
-   "start": "react-scripts start", // delete
+   "start": "craco start", // add
-   "build": "react-scripts build",// delete
+   "build": "craco build"// add
-   "test": "react-scripts test",// delete
+   "test": "craco test"// add
}

4. Configuration file

// craco.config.js
const path = require("path");

const reslove = dir => path.reslove(__dirname, dir);

module.exports = {
    webpack: {
        alias: {
            "@": reslove("src"),
            "components": reslove("src/components")
        }
    }
}

5. usage

// Originally imported
import "./assets/css/reset.css"

// Import now
import "@/assets/css/reset.css"
created at:11-14-2021
edited at: 11-14-2021: