본문 바로가기

개발하자

Svlete: 절대 경로로 가져오기가 작동하지 않습니다.

반응형

Svlete: 절대 경로로 가져오기가 작동하지 않습니다.

파일에 대한 절대 경로를 사용하여 열거형, 객체, 함수 및 svelte 구성 요소를 가져오려고 하지만 컴파일러가 찾을 수 없습니다.

수입하는 방법은 다음과 같습니다.

<script lang=ts>
    import { MyEnum } from "src/lib/enums";
    ... code ...
<script/>

VS Code 컴파일러는 경로에 대해 불평하지 않습니다.

앱을 실행할 때 창에 다음과 같은 오류 메시지가 표시됩니다.

[plugin:vite:import-analysis] Failed to resolve import "src/lib/enums" from "src\lib\GUI\ObjectOnBoard.svelte". Does the file exist?
35 |  
36 |  const { Object: Object_1 } = globals;
37 |  import { MyEnum } from "src/lib/enums";
   |                              ^

몇 가지 조사를 해 본 결과 구성 파일과 관련하여 몇 가지 문제가 있을 수 있다는 것을 알게 되었지만 참조 작업을 위해 이러한 파일을 구성하는 방법을 모르겠습니다. 내 프로젝트의 구성 파일(관련성이 있다고 생각하는 파일)은 다음과 같습니다.

vite.config.ts:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

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

svlete.config.js:

import sveltePreprocess from 'svelte-preprocess'

export default {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
  preprocess: sveltePreprocess(),
}

tsconfig.json:

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "resolveJsonModule": true,
    "baseUrl": ".",
    /**
     * Typecheck JS in `.svelte` and `.js` files by default.
     * Disable checkJs if you'd like to use dynamic types in JS.
     * Note that setting allowJs false does not prevent the use
     * of JS in `.svelte` files.
     */
    "allowJs": true,
    "checkJs": true,
    "isolatedModules": true,
  },
  "include": ["src/**/*.d.ts", "src/**/*.{svelte,ts,js}"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

아래에 주어진 답은 코드를 컴파일하는 데 사용되므로, 이제 실제로 실행되어 훌륭합니다! 그러나 VS Code 자동 완성 및 오류 메시지(빨간색 가늘고 긴 줄)와 관련하여 여전히 문제가 있습니다.

절대 경로를 지정하면 .svelte 파일 내에서 완벽하게 작동하지만, .ts 파일에서는 코드가 컴파일되고 작동하더라도 typescript가 오류를 계속 경고합니다.

"Cannot find module 'src/lib/objects/outlet' or its corresponding type declarations."

이 오류 문은 "src/lib/MainDataStructure" 파일에 나타납니다.

"TS 서버 다시 시작"을 시도해 보았지만 도움이 되지 않습니다. 나는 어떤 것이 이것을 해결할 수 있는 방법에 대한 많은 제안들을 가지고 있는지 살펴보았지만, 나에게는 효과가 없다.

현재 tsconfig.json 파일입니다.

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    /**
     * Typecheck JS in `.svelte` and `.js` files by default.
     * Disable checkJs if you'd like to use dynamic types in JS.
     * Note that setting allowJs false does not prevent the use
     * of JS in `.svelte` files.
     */
    "allowJs": true,
    "checkJs": true,
    "isolatedModules": true,
    "baseUrl": ".",
    "paths": {
      "src/*": [
        "src/*"
      ],
    }
  },
  "include": ["src/**/*.d.ts", "src/**/*.{svelte,ts,js}"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

다음은 프로젝트에 있는 내 디렉토리의 이미지입니다.

enter image description here




노드 모듈 해상도(에 의해 설정됨)에서 이러한 경로는 절대 파일 경로가 아닙니다. 이 경우 노드 모듈에 관련된 것으로 해석됩니다.

로컬 파일을 참조하려면 를 통해 먼저 경로 별칭을 정의해야 할 수 있습니다.

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

이 경우 폴더는 구성과 동일한 수준이어야 합니다.

Vite를 사용할 때 빌드 시스템에서 경로 매핑을 인식해야 할 수도 있습니다. 예를 들어, Vite에 대한 플러그인을 제공하는 패키지가 있습니다.

추가 종속성을 원하지 않거나 이 작업이 작동하지 않는 경우 에서 직접 별칭을 지정할 수 있습니다.

// ...
import path from 'path';

export default defineConfig({
    // ...
    resolve: {
        alias: {
            src: path.resolve('src/'),
        },
    }
});

Vite 구성 단계는 빌드가 작동하기 위해 중요하며, 편집기 툴링을 작동시키기 위해 필요할 수 있습니다(예: VS Code의 코드 완성 및 탐색).


반응형