vue.js 如何解决“无法在'@/...'中解析导入”的问题?

vbopmzt1  于 2023-03-24  发布在  Vue.js
关注(0)|答案(1)|浏览(352)

这是我得到的错误。我在“vite.config.ts”文件中定义的文件路径有问题。你能帮我吗?
Error Log
错误信息:

FAIL  tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ]
Error: Failed to resolve import "@/constant" from "src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts". Does the file exist?

ConvertFromDomainToCountryCode.test.ts文件

import { describe, expect } from "vitest";
import { SetFlags } from "../../src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts";

describe("Convert From Domain To CountryCode", () => {
  test("function defined", () => {
    expect(SetFlags).toBeDefined();
  });
});

在这里,当我将文件路径设置为“../../../constant/index”时,它工作得很好。
ConvertFromDomainToCountryCode.ts文件

import { COUNTRY_INFO } from "@/constant";

这里我加了“别名”
vite.config.ts文件

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve, dirname } from "node:path";
import vueJsx from "@vitejs/plugin-vue-jsx";

export default defineConfig({
  plugins: [
    vue(),
    vueJsx()
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url))
    }
  },
  base: "/"
});

系统

OS: macOS 13.2.1
CPU: (8) arm64 Apple M1 Pro
Memory: 91.50 MB / 16.00 GB
Shell: 5.8.1 - /bin/zsh
Binaries:
Node: 16.18.1 - ~/.nvm/versions/node/v16.18.1/bin/node
Yarn: 1.22.19 - ~/.nvm/versions/node/v16.18.1/bin/yarn
npm: 8.19.2 - ~/.nvm/versions/node/v16.18.1/bin/npm
Browsers:
Chrome: 111.0.5563.64
Safari: 16.3
npmPackages:
@vitejs/plugin-vue: ^3.1.2 => 3.2.0
@vitejs/plugin-vue-jsx: ^3.0.0 => 3.0.0
@vitest/coverage-istanbul: ^0.29.3 => 0.29.3
vite: ^3.1.8 => 3.2.5
vitest: ^0.29.3 => 0.29.3

只是在等待找到文件的路径

eoigrqb6

eoigrqb61#

我解决了这个错误。我添加这个代码在vitest.confic.ts文件。

resolve: {
    alias: [{ find: "@", replacement: resolve(__dirname, "./src") }]
  }

相关问题