react + ts configuration project path name alias (use the @ symbol to report an error when importing)

foreword

During the project development process, when importing the project .tsxinto the page, the file reports an error: The module "@/xxx/xxx" or its corresponding type declaration cannot be found. The main reason is that currently the prompt for the directory pointed to by is not supported, and vite does not support it by default. So you need to manually configure the pointing of the symbolimport.ts
ts@src
@

Configuration of road king aliases

Add configuration in vite.config.ts:

import path from "path"

export default defineConfig({
    
    
  ...
  plugins: [react()],
  resolve: {
    
    
    alias: {
    
    
      "@": path.resolve(__dirname, './src')
    }
  }
})

At this time, the imported pathmodule will report red, but we already have node, paththe module exists, but tssome declaration configurations of are missing, so just install the declaration configuration about nodethis libraryts

npm i -D @types/node

If the installation is successful, there will be no red flags. If importthe following red flags are red, just pathreplace the import withimport * as path from 'path';

Tips for configuring path aliases

Although the alias of Road King already exists, @there is no prompt for Road King when entering in the file.
We need tsconfig.jsonto add two configurations in :

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

After the configuration is completed, @there will be a road resource prompt after writing.

Guess you like

Origin blog.csdn.net/qq_43106047/article/details/129221934