magick-wasm: Can't build in Vite

magick-wasm version

Any

Description

When trying to build with Vite, it gives the following warning, but not always on the same file: 'ws' is imported by ws?commonjs-external, but could not be resolved – treating it as an external dependency It decides to alias ws to require$$2, which doesn’t exist, breaking the build.

I tried installing ws, which stops Vite from complaining. But the build still doesn’t work, saying that Buffer does not exist, suggesting it tries to run in a node environment.

From what I can find, the problematic code resides in @imagemagick/magick-wasm/wasm/magick.js.

Steps to Reproduce

Set up a minimal project (use single -- for npm 6 and under):

npm init vite vite-build-test -- --template vanilla
cd vite-build-test
npm i @imagemagick/magick-wasm

Overwrite main.js to contain only the following:

import { initializeImageMagick } from "@imagemagick/magick-wasm";

Then try npm run build

Optionally serve the freshly created build: npm run preview

Images

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 17 (16 by maintainers)

Commits related to this issue

Most upvoted comments

Finally got the same thing working in Vite! Under the hood it uses Rollup, so using rollup-plugin-ignore and the following config does the trick:

// vite.config.js
import { builtinModules } from "module";
import { defineConfig } from "vite";
import ignore from "rollup-plugin-ignore";

export default defineConfig({
  build: {
    rollupOptions: {
      plugins: [ignore([...builtinModules, "ws"])],
      // or:
      // plugins: [ignore(["ws", "fs", "child_process", "crypto", "path"])],
    },
  },
});

Edit: the ignore plugin isn’t needed when using the build.commonjsOptions.ignore option instead. This also seems to resolve an edgecase where the crypto module would not be ignored properly. So use this instead:

// vite.config.js
import { builtinModules } from "module";
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    commonjsOptions: {
      ignore: [...builtinModules, "ws"],
      // or:
      // ignore: ["ws", "fs", "child_process", "crypto", "path"],
    },
  },
});

I don’t have a plan for this, but I could probably do this tomorrow. Going to be this weekend instead…

By now I’ve spent many hours trying to figure this out and I too can’t find the underlying problem. It seems that @dlemstra/magick-native needs a build step that Vite (Rollup under the hood) can’t provide, also not with polyfills (that is what the linked repository does with Webpack).