从 Webpack 迁移到 Vite:如何解析路径别名并让导入工作

问题描述 投票:0回答:2

我正在将我的项目从 Webpack 迁移到 Vite

"vite": "^4.3.9",

之后

npm start
我收到此错误:

错误:以下依赖项已导入但无法导入 已解决:

在我的 React Typescript 文件中,我像这样导入:

import { cacheOpts, typeDefs } from 'app/graphql/cache';

我需要做什么才能保持所有导入不变?

tsconfig.json
我有:

"baseUrl": "./src",
"paths": {
      "*": ["shared/*", "client/*", "server/*", "*"]
    },

我在

vite.config.ts
看到我可以添加
path.resolve

resolve: {
    alias: {
      src: path.resolve('src/'),
    },
  }

如何让我的导入发挥作用?

reactjs typescript alias vite
2个回答
0
投票

一种常见的技术是使用

resolve
中的
vite.config.ts
部分将“@”符号别名为源目录根目录,这样您就不需要相对路径。即。

import path from 'path';
...
export default defineConfig({
...
    resolve: {
        alias: { '@': path.resolve(__dirname, 'src') },
    },
})

tsconfig.json
中,省略
baseUrl
但使用

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

然后,假设您的

app
文件夹是
src
文件夹的子文件夹,则导入将变为

import { cacheOpts, typeDefs } from '@/app/graphql/cache';

如果您愿意使用相对路径,则可以省略

resolve... alias
中的
vite.config.ts
,并在
tsconfig.json
中使用它:

{
  "compilerOptions": {
    ...
    "baseUrl": "./src"
  },
  "include": ["src"],
  ...
}

0
投票

使用这个包,它很完美,解决了问题
https://www.npmjs.com/package/vite-tsconfig-paths
安装后,去编辑你的vite.config.ts

import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), tsconfigPaths()]
})

© www.soinside.com 2019 - 2024. All rights reserved.