mathe42 / vite-plugin-comlink

Use WebWorkers in Vite with comlink!
MIT License
170 stars 18 forks source link

Cannot use a import outside module #155

Open ShukantPal opened 3 months ago

ShukantPal commented 3 months ago

Describe the bug

I'm developing a Svelte app and tried to add vite-plugin-comlink. Unfortunately, I faced a problem with no workaround w.r.t. loading the plugin:

import { wrap as comlink_wrap } from "comlink";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (node:internal/modules/cjs/loader:1376:18)
    at Module._compile (node:internal/modules/cjs/loader:1405:20)
    at Module._extensions..js (node:internal/modules/cjs/loader:1544:10)
    at Module.load (node:internal/modules/cjs/loader:1275:32)
    at Module._load (node:internal/modules/cjs/loader:1091:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:212:19)
    at cjsLoader (node:internal/modules/esm/translators:318:5)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:258:7)
    at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:474:24

To Reproduce

Have "type": "module" in your package.json and then this plugin.

Desktop (please complete the following information):

Fix

Use CommonJS in symbol.js

const { wrap: comlink_wrap } = require("comlink");
const comlink = {
    proxy,
    proxyMarker,
    finalizer,
    releaseProxy,
    createEndpoint
} = require('comlink');

Object.assign(module.exports, comlink);

const endpointSymbol = module.exports.endpointSymbol = Symbol("getEndpoint");

/**
 * internal API
 */
module.exports.wrap = (ep) => {
    const wrapped = comlink_wrap(ep);
    return new Proxy(wrapped, {
      get(_target, prop, _receiver) {
        if (prop === endpointSymbol) return ep;
        return Reflect.get(...arguments);
      }
    });
}
mathe42 commented 3 months ago

I have a problem with that solution as I don't want to use CommonJS.

Could you provide a full reproduction so I can test some other options?

ShukantPal commented 3 months ago

Sure, I'm building https://github.com/openblitz/www

You can run the build.sh script and then pnpm dev. It works because I have a patch (see patches directory) to modify vite-plugin-comlink to be CommonJS.

I have a problem with that solution as I don't want to use CommonJS.

In that case, you can also set "type": "module" in your package.json. There might be other downstream implications of this change, however; in my testing, that also worked. I only chose to use CommonJS because it's not possible to patch the package.json file using pnpm.

20manas commented 1 month ago

I encountered the exact same issue.

@mathe42 Could you please fix this. Thanks