rollup-plugin-rust icon indicating copy to clipboard operation
rollup-plugin-rust copied to clipboard

Using this plugin with Vite Web Workers

Open DougAnderson444 opened this issue 1 year ago • 1 comments

I am really a big fan of this plugin, thank you for maintaining it!

I have a Vite Web Worker where I'm using this plugin.

Funny enough, it works in dev mode and breaks when I try to build (opposite of what we saw last year. Sigh...)

Is there any chance you know what is going wrong here? It's as if your plugin needs to run first, and have the code transformed before it gets to the worker plugin?

// worker.js
import wasm from '../../../crates/seed-bindgen/Cargo.toml';

export let generate, encrypt, decrypt;

async function init() {
	if (!import.meta.env.SSR) {
		({ generate, encrypt, decrypt } = await wasm());
		console.log('wasm ready', { generate, encrypt, decrypt });
	}
}

init();

// set up web worker messaging
onmessage = async (e) => {
// ...etc
// vit.config.ts
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { viteSingleFile } from 'vite-plugin-singlefile';
import basicSsl from '@vitejs/plugin-basic-ssl';
import svgLoader from 'vite-svg-loader';
import preprocess from 'svelte-preprocess';
import rust from '@wasm-tool/rollup-plugin-rust';

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [
		rust({
			inlineWasm: true
		}),
		svelte({
			preprocess: preprocess()
		}),
		// basicSsl(),
		viteSingleFile(),
		svgLoader({
			defaultImport: 'raw'
		})
	],
	build: {
		cssCodeSplit: false,
		assetsInlineLimit: 2097152, // 2MB = 1024 * 1024 * 2 = 2097152
		rollupOptions: {}
	},
	// no strict fs server
	server: {
		fs: {
			strict: false
		}
	},
	// worker format
	worker: {
		format: 'es'
	}
});

The error log

Error [RollupError]: The keyword 'package' is reserved (Note that you need plugins to import files that are not JavaScript)
  code: 'PLUGIN_ERROR',
  frame: '1: [package]\n    ^\n2: edition = "2021"\n3: name = "seed-bindgen"',
  pluginCode: 'PARSE_ERROR',
  plugin: 'vite:worker-import-meta-url',
  hook: 'transform'
}

Node.js v18.5.0

DougAnderson444 avatar Aug 11 '23 18:08 DougAnderson444

Ok, I've found a work around which kind of confirms there's a Vite bug with their rollup plugins still

Workaround:

Add the @wasm-tool/rollup-plugin-rust to the build.rollupOptions.plugins array:

/// vite.config.ts
export default defineConfig({
	plugins: [
		rust({
			inlineWasm: true
		}),
		// ...
	],
	build: {
		rollupOptions: {
			plugins: [
				rust({
					inlineWasm: true // <== needed here for build step 
				})
			]
		}
	},
	// worker format
	worker: {
		format: 'es'
	}
});

DougAnderson444 avatar Aug 11 '23 21:08 DougAnderson444