Skip to content

Vite compiler dev mode, option to add type = module to all js assets #1

@brychanmd

Description

@brychanmd

I noticed when trying to import and use an icon library that I could not add imports to the app.js file in the TailPress theme.

I was getting the following console error:

Uncaught SyntaxError: import declarations may only appear at top level of a module in [app.js:1:1](http://localhost:3000/resources/js/app.js)

Noticed that the app.js file was of type text/javascript not module so can't add imports.

Dug into the register assets stuff in the TailPress Framework (ViteCompiler.php) and noticed that you have a filter to apply type = module to the vite client but nothing else, so I removed the if statement and now it's applying type module to the app.js. I can now use module imports in my js resources.

            add_filter('script_loader_tag', function ($tag, $handle) {
                if (in_array($handle, ['vite-client', $this->handle], true)) {
                    $tag = str_replace('<script ', '<script type="module" ', $tag);
                }

                return $tag;
            }, 10, 2);
            add_filter('script_loader_tag', function ($tag) {
                $tag = str_replace('<script ', '<script type="module" ', $tag);
                return $tag;
            }, 10, 2);

Any way to add configuration or something to be able to enqueue js assets as type module?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions