简体   繁体   中英

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

I used a few web components in my Svelte project, but after running npm run dev (which is vite dev actually), error HTMLElement is not defined shows up.

The whole error message is

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)

The problematic line of code is

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

But it works fine in Storybook. No error shows up there.

Could anyone teach me how to solve it please?

Thanks in advance!

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
        }
    }
};

It is because web components cannot be rendered in server side.

To solve it, use dynamic import like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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