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

此插件不支持`new URL(..., import.meta.url)`形式的依赖。

Open heroboy opened this issue 2 months ago • 3 comments

wasm在js文件是这样引入的

function findWasmBinary() {
  if (Module['locateFile']) {
    var f = 'minisat_static.wasm';
    if (!isDataURI(f)) {
      return locateFile(f);
    }
    return f;
  }
  // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too.
  return new URL('minisat_static.wasm', import.meta.url).href;
}

在build的时候,这是正常的new URL这段被替换成了data url。 但在dev模式下,这个wasm文件是不是应该复制到deps目录呢?我不是很了解vite,不知道应该如何配置。

heroboy avatar Nov 07 '25 01:11 heroboy

经过研究,上面这种new URL形式,不能通过externalResource形式替换成GM_getResourceURL(...)。 另外只能通过,在vite.config.ts里写plugin来阻止inline。

主要是生成的dist文件太大了,vscode一打开ts扩展就死机,不想要inline。

heroboy avatar Nov 10 '25 03:11 heroboy

我觉得应该参考这段代码:https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/assetImportMetaUrl.ts

heroboy avatar Nov 10 '25 03:11 heroboy

折腾了一下,写了一下plugin。同时适用于build和serve模式。 在build中,使用GM_getResourceURL读取wasm,在serve中,使用publicDir来读取wasm。暂时,在我的能力中,没有比这个更“正确”的做法了。

{
			name: 'vite-plugin-my-plugin',
			enforce: 'pre',
			config(_, env)
			{
				if (env.command === 'build')
				{
					return {
						publicDir: false,
						build: {
							assetsInlineLimit(filePath, content)
							{
								return false;
							},
						}
					};
				}
				else//serve
				{
					return {
						publicDir:'node_modules/logic-solver-plus/mjs'
					};
				}
			},
			transform(code, id, options)
			{
				if (this.environment.config.command === 'build')
				{
					const m = /new URL\(.+minisat_static\.wasm.+\)/.exec(code);
					if (m)
					{
						this.info('ok transform my wasm');
						const ms = new MagicString(code);
						ms.update(m.index!, m.index! + m[0].length, "new URL(GM_getResourceURL('minisat_static.wasm').replace('application','application/wasm'))");
						return { code: ms.toString(), map: ms.generateMap() };
					}
				}
				else//serve
				{
					const m = /new URL\(.+minisat_static\.wasm.+\)/.exec(code);
					if (m)
					{
						this.info('ok transform my wasm');
						const ms = new MagicString(code);
						ms.update(m.index!, m.index! + m[0].length, "new URL('/minisat_static.wasm',import.meta.url)");
						return { code: ms.toString(), map: ms.generateMap() };
					}
				}

			}
		}

heroboy avatar Nov 10 '25 06:11 heroboy

https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/assetImportMetaUrl.ts

heroboy avatar Dec 16 '25 00:12 heroboy