Skip to content

SvelteKit: "unexpected token 'export'" when using GooglePlacesAutocomplete #19

@dennisjlee

Description

@dennisjlee

In SvelteKit (which uses Vite as a dev server), there seems to be an issue importing @beyonk/async-script-loader, which is a dependency of @beyonk/svelte-googlemaps.

When I added a to my SvelteKit page, the page wasn't able to render via SSR, with this error:

Unexpected token 'export'
C:\Users\[...redacted...]\node_modules\@beyonk\async-script-loader\index.js:1
export default function (urls, test, callback) {
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at nodeRequire (C:\Users\[...redacted...]\node_modules\vite\dist\node\chunks\dep-c1a9de64.js:73479:17)
    at ssrImport (C:\Users\[...redacted...]\node_modules\vite\dist\node\chunks\dep-c1a9de64.js:73431:20)
    at eval (/node_modules/@beyonk/svelte-googlemaps/src/GoogleSdk.svelte:7:31)

There is some more info on how Vite behaves here: https://vitejs.dev/guide/ssr.html#ssr-externals

I was able to successfully apply one of the workarounds there by adding this to my svelte.config.js file:

    vite: {
      ssr: {
        // Vite's heuristic does not work properly for this ESM-only library for
        // some reason, and it tries to import it as a CommonJS module.
        // Adding the library to noExternal avoids this problem. The symptoms
        // were "SyntaxError: Unexpected token 'export'" in SSR or when building
        // the app for production.
        noExternal: ['@beyonk/async-script-loader']
      }
    }

I'm not sure what the appropriate permanent fix might be here - perhaps a change to package.json in @beyonk/async-script-loader could help inform Vite that the package is ESM-only. (I tried adding "type": "module" to that package.json but that didn't work.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions