如何让 vite 编译含有 Node.js 模块的 TS 文件 ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING

背景

假如我们的包有个脚本 scripts/check-authorization-update.ts 使用 ts 写的,但是目前(2025-4-10 v23)Node.js 并不支持也不打算支持运行 node_modules 内的 ts 文件(deno 可以),否则会报错 Error [ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING]: Stripping types is currently unsupported for files under node_modules

有几种解决办法:

  1. 【不编译】 重写成 mjs,能最小改动,因为可以保留 import / export 只需将类型改成 tsdoc。
  2. 【不编译】 将需要直接加载的 .ts 文件移出 node_modules 目录,因为 Node.js 对 node_modules 目录下的文件有特殊的处理逻辑,不支持直接加载 TypeScript 文件[1]。这个很巧妙,但是需要再写一个脚本。
  3. 【编译】vite。

本文列举一个通过 vite 编译的方式,将脚本编译为 js。设置如下:

diff 复制代码
index f23ccf7..b3fdc86 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -30,12 +30,18 @@ export default defineConfig({
     sourcemap: true,
 
     lib: {
-      entry: resolve(__dirname, 'src/index.ts'),
+      entry: [
+        resolve(__dirname, 'src/index.ts'),
+        resolve(__dirname, 'scripts/check-authorization-update.ts'),
+      ],
       formats: ['es'],
       fileName: (_format, entryName) => `${entryName}.js`,
     },
 
     rollupOptions: {
+      // 外部化处理 Node.js 原生模块和不想打包在内 node 三方模块(tar)
+      external: ['node:fs', 'node:fs/promises', 'node:path', 'node:https', 'tar'],
+
       output: {
         preserveModules: true, // 保留模块结构,便于 Tree Shaking
       }
相关推荐
bingbingyihao9 小时前
Node.js 模拟 Linux 环境
linux·node.js
前端工作日常12 小时前
ESLint 配置深度解析:parserOptions、env 和 flowtype 的核心作用与实战指南
typescript·eslint
吳所畏惧12 小时前
NVM踩坑实录:配置了npm的阿里云cdn之后,下载nodejs老版本(如:12.18.4)时,报404异常,下载失败的问题解决
前端·windows·阿里云·npm·node.js·batch命令
前端拿破轮12 小时前
2025年了,你还不知道怎么在vscode中直接调试TypeScript文件?
前端·typescript·visual studio code
JS_Love14 小时前
nodejs 手动实现 multipart/byteranges 分块下载
node.js
白一梓15 小时前
Node.js 流全解
node.js
天文家18 小时前
关于TypeScript中type和interface的区别与作用场景
typescript
lichenyang4531 天前
Axios封装以及添加拦截器
前端·javascript·react.js·typescript
太阳上的雨天1 天前
与 TRON (波场) 区块链进行交互的命令行工具 (CLI): tstroncli
typescript·区块链·交互·tron·trx·trc20
门前云梦1 天前
ollama+open-webui本地部署自己的模型到d盘+两种open-webui部署方式(详细步骤+大量贴图)
前端·经验分享·笔记·语言模型·node.js·github·pip