我正在尝试在使用 SvelteKit、TypeScript 和 Vite 制作的 Web 应用程序中使用 OpenPGP.js V6。
OpenPGP.js V6 现在声明为模块,我无法找到使用当前堆栈正确导入它的方法。
我首先尝试按照文档的建议在我的 Svelte 组件中导入 openpgp :
<script lang="ts">
import * as openpgp from "openpgp";
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
<p>{ JSON.stringify(openpgp.config) }</p>
我导致浏览器错误:
TypeError: import_module.createRequire is not a function
<anonymous> openpgp.mjs:1767
使用轻量级模块<script lang="ts">
import * as openpgp from "openpgp/lightweight";
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
<p>{ JSON.stringify(openpgp.config) }</p>
这会导致 Vite 错误:
[plugin:vite:import-analysis] Missing "./" specifier in "openpgp" package
直接导入.mjs文件
<script lang="ts">
import * as openpgp from "../../node_modules/openpgp/dist/openpgp.mjs";
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
<p>{ JSON.stringify(openpgp.config) }</p>
这可以在浏览器中运行,但会出现 TypeScript 错误:
Could not find a declaration file for module '../../node_modules/openpgp/dist/openpgp.mjs'. '/.../test-app/node_modules/openpgp/dist/openpgp.mjs' implicitly has an 'any' type.ts(7016)
我当然可以//@ts-ignore
,但它会消除使用 TypeScript 的大部分好处。背景
npx sv create my-app
)来重现该问题。package.json(请注意,我还安装了
@openpgp/web-stream-tools
,如文档建议):
{
"name": "test-app",
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@openpgp/web-stream-tools": "^0.1.3",
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"@types/node": "^22.9.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0",
"vite": "^5.0.3"
},
"dependencies": {
"openpgp": "^6.0.0"
}
}
vite.config.ts:
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
});
svelte.config.js:
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
export default config;
tsconfig.json:
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}