The project configuration @alias path, and let the editor correctly identify and prompt.

foreword

Configuring an alias path in a project is a common operation when writing a project. The benefits are:

  1. Simplify module paths. In a project, some files may exist in deep directories and need to be referenced multiple times. If you use relative paths for references every time, it will be very troublesome. By configuring the @alias path in the project  , the path of these deep directories can be simplified into an alias, which is more clear and concise in the code.

  2. Improve refactoring efficiency. It is often necessary to refactor files in projects, such as moving a component from one directory to another. If the alias path is not used for reference, it is necessary to modify the path in all places where the component is referenced, which is very time-consuming and laborious. If you use an alias path, you only need to modify it in the configuration of the alias path.

  3. Easy maintenance. In a large-scale project, there will be many shared components, tools and other resources, and these resources often need to be referenced in different places. If alias paths are not used, problems such as missing references or duplicate definitions may occur. The use of alias paths can avoid these problems, manage shared resources in the project in a unified manner, and be easy to identify and maintain in the code.

configuration

  • Fast
import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})
  • Webpack
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

Editor recognition

jsconfig.jsonThe editor does not automatically recognize the alias, you also need to add a (or ) file to the project tsconfig.jsonand configure the alias in it.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_42373175/article/details/130953352