繁体   English   中英

在 Svelte 和 Vite 中,运行“npm run dev”后出现错误“HTMLElement is not defined”

[英]In Svelte and Vite, error "HTMLElement is not defined" shows up after running "npm run dev"

我在我的 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
        }
    }
};

这是因为 web 个组件无法在服务端渲染。

要解决它,请使用动态导入之类的

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM