javascriptnode.jsimportweb-workervite

What are the "Query Suffixes" referred to in the Vite Docs?


I have been reading through the Vite documentation for Web workers, and it mentioned importing a file using "Query Suffixes," which I have never encountered and am not sure what to search for to learn more. I'm not sure if this is native to Node.js, Vite.js, or if it is a plugin that is built into Vite.

This is the specific section that I am referring to:


Import with Query Suffixes

A web worker script can be directly imported by appending ?worker or ?sharedworker to the import request. The default export will be a custom worker constructor:

import MyWorker from './worker?worker'

const worker = new MyWorker()

The worker script can also use import statements instead of importScripts() - note during dev this relies on browser native support and currently only works in Chrome, but for the production build it is compiled away.

By default, the worker script will be emitted as a separate chunk in the production build. If you wish to inline the worker as base64 strings, add the inline query:

import MyWorker from './worker?worker&inline'

If you wish to retrieve the worker as a URL, add the url query:

import MyWorker from './worker?worker&url'

See Worker Options for details on configuring the bundling of all workers.


Update:

I found an MDN page on import that seems like a step in the direction that I am looking for, as well as this MDN page on import.meta that looks a lot like what I am searching for. I tried following that lead, but it didn't help me understand this Vite feature any better.

Is the ?worker query suffix a custom Vite implementation of import.meta?


Solution

  • This is a form of import used by vite. It allows the user to be provided with custom imports. In the case of the webworkers it offers a custom constructor so that instead of using the complete syntax

    const worker = new Worker(new URL('./worker.js', import.meta.url))
    

    you can instanciate your worker like this

    import ShortWorker from './worker.js?worker'
    
    const worker = new ShortWorker();
    

    This feature is also used in other cases to allow the user to choose the way files/assets are loaded:

    // Explicitly load assets as URL
    import assetAsURL
     from './asset.js?url'
    
    // Load assets as strings
    import assetAsString
     from './shader.glsl?raw'
    
    // Load Web Workers
    import Worker
     from './worker.js?worker'