vite-plugin-comlink icon indicating copy to clipboard operation
vite-plugin-comlink copied to clipboard

Cannot use a import outside module

Open ShukantPal opened this issue 7 months ago • 3 comments

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):

  • OS: macOS
  • Node.js: 20.x.x and 22.x.x

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

ShukantPal avatar Jul 05 '24 22:07 ShukantPal