You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte项目中import type { User }引发ParseError问题

Svelte中import type触发ParseError: Unexpected token的解决方法

问题场景

在基于Rollup的Svelte项目中执行npm run dev时,出现解析错误,报错信息如下:

$ npm run dev 

> svelte-app@1.0.0 dev
> rollup -c -w

rollup v3.22.0
bundles src/main.js → public/build/bundle.js...
[!] (plugin svelte) ParseError: Unexpected token
src/App.svelte
4:     import { supabase } from "$lib/db";
5:     import Auth from "$lib/Auth.svelte";
6:     import type { User } from "@supabase/supabase-js";
                   ^
7:     import Home from "$lib/Home.svelte";

项目依赖配置(package.json):

{
  "name": "svelte-app",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public --no-clear"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.0",
    "@rollup/plugin-terser": "^0.4.0",
    "@tsconfig/svelte": "^4.0.1",
    "concurrently": "^8.0.1",
    "rollup": "^3.15.0",
    "rollup-plugin-css-only": "^4.3.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.1.2",
    "svelte": "^3.59.1",
    "svelte-check": "^3.3.2",
    "svelte-hcaptcha": "^0.1.1",
    "svelte-preprocess": "^5.0.3",
    "tailwindcss": "^3.3.2",
    "tslib": "^2.5.2",
    "typescript": "^5.0.4",
    "vite": "^4.3.8"
  },
  "dependencies": {
    "@supabase/supabase-js": "^2.22.0",
    "sirv-cli": "^2.0.0"
  }
}

问题原因

Svelte 3本身不具备TypeScript语法解析能力,import type是TypeScript专属语法,未经过预处理的话,Rollup的svelte插件会将其识别为无效JavaScript语法,从而抛出Unexpected token错误。

解决方案

1. 配置Rollup使用svelte-preprocess处理TypeScript

修改项目根目录的rollup.config.js,在svelte插件中引入并配置svelte-preprocess:

import svelte from 'rollup-plugin-svelte';
import preprocess from 'svelte-preprocess';
// 其他必要的导入...

export default {
  // 其他配置...
  plugins: [
    svelte({
      preprocess: preprocess({
        typescript: true
      }),
      // 保留原有的svelte配置(比如css、compilerOptions等)
    }),
    // 其他插件...
  ]
};

2. 配置TypeScript编译规则

确保项目根目录存在tsconfig.json,并继承@tsconfig/svelte的配置:

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "module": "ESNext",
    "target": "ESNext",
    "strict": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules/*", "public/*"]
}

3. 重启开发服务

重新执行npm run dev,错误即可消除。

内容的提问来源于stack exchange,提问作者flyingfishcattle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:00:34