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

在SvelteKit+Vite+TS环境中无法正确引入OpenPGP.js V6的问题

解决SvelteKit+TypeScript+Vite环境下OpenPGP.js V6的正确引入方案

核心解决步骤

通过调整Vite配置+标准ES模块引入,既能正常运行又保留TypeScript类型校验:

1. 安装正确依赖

执行命令安装OpenPGP.js V6:

npm install openpgp@^6

2. 配置Vite修复模块解析问题

在项目根目录的vite.config.ts中添加别名配置,解决轻量模块的路径错误:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
	plugins: [sveltekit()],
	resolve: {
		alias: {
			'openpgp/lightweight': 'openpgp/dist/openpgp-lightweight.mjs'
		}
	}
});

3. 正确引入模块(带类型支持)

根据需求选择对应引入方式:

  • 完整功能模块:
import * as openpgp from 'openpgp';
  • 轻量核心模块:
import * as openpgp from 'openpgp/lightweight';

各问题根因说明

  • TypeError: import_module.createRequire is not a function:官方部分示例混用了Node.js的CommonJS语法,前端运行时不支持createRequire,改用纯ES模块引入即可避免。
  • [plugin:vite:import-analysis] Missing "./" specifier:Vite对包内子路径的解析规则限制,通过配置别名指定明确的文件路径就能解决。
  • TypeScript找不到声明文件:直接引入dist下的mjs文件时,TS无法自动关联包内置的类型声明(位于openpgp/dist/types),用标准包名引入则会自动识别类型定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:15:04