typescript 在Svelte和Vite中,运行“npm run dev”后显示错误“HTMLElement is not defined”(未定义HTMLElement)

ncecgwcz  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(488)

我在我的Svelte项目中使用了一些Web组件,但是在运行npm run dev(实际上是vite dev)之后,出现了错误HTMLElement is not defined
整个错误消息是

HTMLElement is not defined
ReferenceError: HTMLElement is not defined
    at /src/components/shared/formkit/classes/composite.js:21:39
    at async instantiateModule (file:///D:/my_project/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:50548:9)

有问题的代码行是

// File name is composite.js
export class FormKitComposite extends HTMLElement {

但在Storybook中运行良好,没有出现错误。
有人能教我怎么解吗?
提前感谢!
tsconfig.json

{
    "extends": "./.svelte-kit/tsconfig.json",

    "compilerOptions": {
        "allowJs": true,
        "checkJs": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "noImplicitAny": true,
        "noUnusedLocals": true,
        "resolveJsonModule": true,
        "skipLibCheck": true,
        "sourceMap": true,
        "strict": true,
        
        "types": [
            "@testing-library/jest-dom",
            "vitest/globals"
        ]
    },

    "include": [
        "decs.d.ts"
    ]
}

vite.config.ts

const config: UserConfig = {
    plugins: [sveltekit()],

    resolve: {
        alias: {
            $components: path.resolve('src/components'),
            $functions: path.resolve('src/functions'),
            $graphql: path.resolve('src/graphql'),
            $stores: path.resolve('src/stores'),
            $styles: path.resolve('src/styles'),
            $types: path.resolve('src/types')
        }
    },

    server: {
        fs: {
            strict: false
        }
    },

    test: {
        environment: 'jsdom',
        globals: true,
        include: ['src/components/**/*.test.ts', 'src/functions/**/*.test.ts'],
        setupFiles: ['./setup-test.ts'],

        coverage: {
            branches: 100,
            functions: 100,
            lines: 100,
            statements: 100
        }
    }
};
ujv3wf0j

ujv3wf0j1#

这是因为Web组件无法在服务器端呈现。
要解决此问题,请使用动态导入,如

onMount(async () => {
        await import('your file URL');
    });

相关问题