Search code examples
javascriptwebassemblyweb-worker

WebAssembly exported function: Cannot read properties of undefined


I'm trying to run lightningcss on a WebWorker module for my JavaScript application.

I imported it as a module as follows:

import * as lightningcss from './index.mjs';

and tried using the function as below:

let code = lightningcss.transform({
    code: bufferedTextInput,
    minify: true,
    sourceMap: false
});

However, on running the script in my browser, I encountered the following error:

index.mjs:41 Uncaught TypeError: Cannot read properties of undefined (reading 'transform')
    at Module.transform (index.mjs:41:15)
    at wasm-worker.js:9:29

I tried troubleshooting on the web but to no avail. How would I go about fixing this problem?


Solution

  • The parser should be executed not in the browser but in the node environment.Which means that it should first parse the css and only then send it to the browser. I advise you to understand the principles of how bundlers and parsers work, and how JavaScript works in different environments. nodejs/browser, npm and about runtime and development environment Link to documentation

    Use it with parcel as shown in the documentation.

    import { transform } from 'lightningcss';
    
    let { code, map } = transform({
      filename: 'style.css',
      code: Buffer.from('.foo { color: red }'),
      minify: true,
      sourceMap: true
    });
    

    don't forget to install it first

    npm install --save-dev lightningcss