antvis / layout

Layout algorithms for graphs.
207 stars 55 forks source link

chore: update usage with Webpack & Vite #158

Closed xiaoiver closed 1 year ago

xiaoiver commented 1 year ago

Webpack

Webpack has good support for Webworker, here's an example on Stackblitz. We use statikk as static server in this example since it has a good support of cross-origin isolation headers. For more information, please refer to Use WASM with multithreads.

Vite

Vite also provides worker options in its config. To let Vite process URL correctly when creating WebWorker in third-party packages, we need to add the package to optimizeDeps.exclude:

// vite.config.js
optimizeDeps: {
  exclude: ['@antv/layout-wasm'],
},

To enable COOP & COEP headers, we can set them with plugins:

// vite.config.js
plugins: [
  {
    name: 'isolation',
    configureServer(server) {
      // @see https://gist.github.com/mizchi/afcc5cf233c9e6943720fde4b4579a2b
      server.middlewares.use((_req, res, next) => {
        res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
        res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
        next();
      });
    },
  },
],

Here's a complete example on Stackblitz.

If you can't control the server, try this hacky workaround which implemented with ServiceWorker: https://github.com/orgs/community/discussions/13309#discussioncomment-3844940