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

如何在Vite(SvelteKit模板)环境中运行命令行TypeScript脚本?

需求完全可行,以下是具体实现方案

1. 基础TypeScript语法支持

Node 20.5原生支持ES模块,只需调整项目的tsconfig.json配置以匹配Node的ES模块规则:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2020",
    "strict": true,
    "skipLibCheck": true
  }
}

可以直接用vite-node或tsx工具运行TS脚本,无需手动编译:

# 使用vite-node(推荐,兼容Vite生态)
npx vite-node your-script.ts

# 或使用tsx
npx tsx your-script.ts

2. 支持文本类静态资源导入(如?raw后缀)

vite-node是Vite官方提供的Node运行工具,完全兼容Vite的资源导入语法,直接支持?raw、?url等后缀。安装后即可在脚本中直接写:

import shaderAsString from './shader.glsl?raw';
console.log(shaderAsString);

3. 读取环境变量(import.meta.env)

  • vite-node会自动加载项目根目录的.env文件,遵循SvelteKit的环境变量规则(默认仅加载前缀为VITE_的变量)。
  • 脚本中可直接访问import.meta.env,比如import.meta.env.PROD会根据运行模式自动切换:
    # 开发模式(默认)
    npx vite-node your-script.ts
    # 生产模式
    npx vite-node --mode production your-script.ts
    
  • 若需自定义环境变量前缀,可在vite.config.ts中配置envPrefix。

4. 共享服务器端后端代码

SvelteKit的服务器端代码(如src/lib/server/下的函数)本身就是Node兼容的TS代码,只需在脚本中使用正确的相对路径导入即可:

import { sharedServerFunction } from './src/lib/server/utils.ts';
sharedServerFunction();

注意确保共享的函数不依赖前端专属API(如window、document),仅保留纯逻辑或Node兼容的代码。

内容的提问来源于stack exchange,提问作者Pablo De Napoli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:02:18