본문 바로가기

개발하자

Svelte/Typescript 오류: 형식 선언 중 "예상치 못한 토큰"

반응형

Svelte/Typescript 오류: 형식 선언 중 "예상치 못한 토큰"

그래서 나는 TypeScript가 활성화된 애플리케이션을 가지고 있지만 지금 그것을 실행하는 데 문제가 있다:

[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src\api.ts (4:7)
2:
3: export default class API {
4:     url:string;
          ^
5:

예전에 앱이 작동하다가 갑자기 이런 오류가 발생해서 이해가 안 돼요. Svelte용 TypeScript와 관련된 일부 버전이 변경된 것으로 보인다:

{
  "name": "...",
  "version": "...",
  "private": ...,
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public --no-clear",
    "validate": "svelte-check",
    "check": "svelte-check --tsconfig ./tsconfig.json"  /* + ADDED */
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "...",
    "@rollup/plugin-json": "...",
    "@rollup/plugin-node-resolve": "^13.1.3",
    "@rollup/plugin-typescript": "^8.0.0",
    /* @smui/... stuffs */
    "@tsconfig/svelte": "^2.0.0",     /* ^1.0.0 -> ^2.0.0 */
    "rollup": "^2.67.0",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.5",
    "rollup-plugin-svelte": "^7.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "svelte": "^3.46.3",
    "svelte-check": "^2.0.0",         /* ^1.0.0 -> ^2.0.0 */
    "svelte-preprocess": "^4.0.0",
    "tslib": "^2.0.0",
    "typescript": "^4.0.0"
  },
  "dependencies": {
    "sirv-cli": "^2.0.2",
    "svelte-material-ui": "..."
  }
}
/* Note: I replaced some unrelated properties/version by '...'. */

물론 실행하는 것은 도움이 되지 않았다. 를 제거하면 코드의 다른 모든 오류가 동일하게 발생합니다.

파일 이름이 지정되어 있고 VSCode는 해당 파일에서 구문 오류를 검색하지 않습니다.

구성 파일(편집)

/* tsconfig.json */
{
  "extends": "@tsconfig/svelte/tsconfig.json",

  "include": ["src/**/*"],
  "exclude": ["node_modules/*", "__sapper__/*", "public/*"]
}
/* rollup.config.js */
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '@rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

function serve() {
    let server;

    function toExit() {
        if (server) server.kill(0);
    }

    return {
        writeBundle() {
            if (server) return;
            server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
                stdio: ['ignore', 'inherit', 'inherit'],
                shell: true
            });

            process.on('SIGTERM', toExit);
            process.on('exit', toExit);
        }
    };
}

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                dev: !production
            }
        }),
        css({ output: 'bundle.css' }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs(),
        typescript({
            sourceMap: !production,
            inlineSources: !production
        }),
        json(),
        !production && serve(),
        !production && livereload('public'),
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

파일 없음




그래서 저는 도커 컨테이너에서 앱을 실행하여 작동하는지 확인해 보았습니다. 그리고 훨씬 더 도움이 되는 다른 오류 메시지를 받았습니다:

[!] Error: Could not resolve './api.js' from src/App.js`

실제로 파일 이름은 지정되지 않았지만(파일 이름을 TS로 변경한 후 가져오기를 변경하지 않았습니다...)

그래서 나는 수입을 그렇게 바꿨다:

/* Before (not working) */
import API from './api.js'
/* After (Good) */
import API from './API' 

// NB. The filename is really in uppercase for me

TL;DR

  • 가져오기에서 TS 파일이어야 하는 파일을 확인하고 다음으로 대체합니다(확장자를 작성하면 안 됨)

설명:

자바스크립트() 파일을 가져오려고 하지만, () TypeScript 파일을 찾아서 () 대신 가져오려고 하지만, TypeScript 지원 없이는 파일 내에서 TypeScript 구문을 재설정하지 않는 이상한 상황이 발생한다.




Typescript가 활성화된 최신 svelte 템플릿에서 프로젝트를 설정한 후 코드 편집기가 아닌 서버에서 .svelte 파일로 유형을 가져오려고 할 때 유사한 "예상치 못한 토큰" 불만이 발생했습니다.

수정은 svelte.config.js의 전처리 옵션을 명시적으로 로 설정하는 것이었다. 설정 중에 유형 스크립트가 활성화된 경우 기본적으로 포함된다는 svelte 문서(현재)에서 설명하기 때문에 이는 예상치 못한 것입니다!

import { vitePreprocess } from '@sveltejs/kit/vite';
 
export default {
  preprocess: [vitePreprocess()]
};

반응형