Recently, I was developing a new project and time was urgent, so I didn’t have time to browse technical articles to accumulate new knowledge. But as long as the heart, thinking, in business development can also precipitate technology.

This project is built using create-React-app and typescript. Since this is the first time to build a full project in typescript (previously just writing components in typescript), I encountered a lot of pitfalls.

Today we will share the first pit: configuring path aliases.

For general projects, we can set them up in the webpack.base.config file

Webpack. Base. The config file... module.exports = { ... resolve: {alias: {
          The '@': src } } ... }...Copy the code

Create-react-app does not have this file, because the scaffolding has all the Settings set by default. If you want to change them, you need to create a new config-overrides.

Most of the information online is in two steps:

1. Modify config-overrides. Js:

const { override, addWebpackAlias, addDecoratorsLegacy } = require('customize-cra');
const path = require('path')

module.exports = override(
  addWebpackAlias({
    "@": path.resolve(__dirname, 'src')
  }),
  addDecoratorsLegacy(), 
);
Copy the code

2. Add the Paths configuration item in the tsconfig.json file:

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

Change the import mode of Component in app.tsx to:

import component from '@/component'
Copy the code

Error: Cannot find module ‘@/ Component ‘when NPM run start starts project. Now you look like this ↓ ↓

If you look in the tsconfig.json file, paths is missing! Do you have many question marks?

The solution

To solve the problem in step 2, create a paths.json file in the project root directory (SRC sibling directory). The specific file name can be modified by adding the following content:

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

Then modify it in tsconfig.json:

"extends": "./paths.json"
Copy the code

Ok, perfect solution.