Skip to content

Commit 42a8693

Browse files
committed
refactor: move to module runner
Related: #1214. Related: #1044.
1 parent 5f574b4 commit 42a8693

File tree

5 files changed

+69
-58
lines changed

5 files changed

+69
-58
lines changed

packages/wxt/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,10 @@
5858
"publish-browser-extension": "^2.3.0 || ^3.0.2",
5959
"scule": "^1.3.0",
6060
"unimport": "^3.13.1 || ^4.0.0 || ^5.0.0",
61-
"vite-node": "^2.1.4 || ^3.1.2",
6261
"web-ext-run": "^0.2.4"
6362
},
6463
"peerDependencies": {
65-
"vite": "^5.4.19 || ^6.3.4 || ^7.0.0"
64+
"vite": "^6.3.4 || ^7.0.0"
6665
},
6766
"devDependencies": {
6867
"@aklinker1/check": "^2.1.0",

packages/wxt/src/core/builders/vite/index.ts

Lines changed: 66 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@ import {
2121
import { Hookable } from 'hookable';
2222
import { toArray } from '../../utils/arrays';
2323
import { safeVarName } from '../../utils/strings';
24-
import { ViteNodeServer } from 'vite-node/server';
25-
import { ViteNodeRunner } from 'vite-node/client';
26-
import { installSourcemapsSupport } from 'vite-node/source-map';
2724
import { createExtensionEnvironment } from '../../utils/environments';
2825
import { dirname, extname, join, relative } from 'node:path';
2926
import fs from 'fs-extra';
@@ -71,7 +68,6 @@ export async function createViteBuilder(
7168

7269
// TODO: Remove once https://github.com/wxt-dev/wxt/pull/1411 is merged
7370
config.legacy ??= {};
74-
// @ts-ignore: Untyped option:
7571
config.legacy.skipWebSocketTokenCheck = true;
7672

7773
const server = getWxtDevServer?.();
@@ -90,8 +86,9 @@ export async function createViteBuilder(
9086
wxtPlugins.resolveAppConfig(wxtConfig),
9187
);
9288
if (
89+
// TODO: Should this be migrated to use perEnvironmentState?
9390
wxtConfig.analysis.enabled &&
94-
// If included, vite-node entrypoint loader will increment the
91+
// If included, entrypoint loader will increment the
9592
// bundleAnalysis's internal build index tracker, which we don't want
9693
!baseConfigOptions?.excludeAnalysisPlugin
9794
) {
@@ -224,8 +221,7 @@ export async function createViteBuilder(
224221
},
225222
};
226223
};
227-
228-
const createViteNodeImporter = async (paths: string[]) => {
224+
const createImporterEnvironment = async (paths: string[]) => {
229225
const baseConfig = await getBaseConfig({
230226
excludeAnalysisPlugin: true,
231227
});
@@ -238,33 +234,47 @@ export async function createViteBuilder(
238234
wxtPlugins.removeEntrypointMainFunction(wxtConfig, path),
239235
),
240236
};
241-
const config = vite.mergeConfig(baseConfig, envConfig);
242-
const server = await vite.createServer(config);
243-
await server.pluginContainer.buildStart({});
244-
const node = new ViteNodeServer(
245-
// @ts-ignore: Some weird type error...
246-
server,
237+
const importerConfig = vite.mergeConfig(baseConfig, envConfig);
238+
239+
const config = await vite.resolveConfig(
240+
vite.mergeConfig(importerConfig || {}, {
241+
configFile: false,
242+
envDir: false,
243+
cacheDir: process.cwd(),
244+
environments: {
245+
inline: {
246+
consumer: 'server',
247+
dev: {
248+
moduleRunnerTransform: true,
249+
},
250+
resolve: {
251+
external: true,
252+
mainFields: [],
253+
conditions: ['node'],
254+
},
255+
},
256+
},
257+
} satisfies vite.InlineConfig),
258+
'serve',
247259
);
248-
installSourcemapsSupport({
249-
getSourceMap: (source) => node.getSourceMap(source),
250-
});
251-
const runner = new ViteNodeRunner({
252-
root: server.config.root,
253-
base: server.config.base,
254-
// when having the server and runner in a different context,
255-
// you will need to handle the communication between them
256-
// and pass to this function
257-
fetchModule(id) {
258-
return node.fetchModule(id);
259-
},
260-
resolveId(id, importer) {
261-
return node.resolveId(id, importer);
260+
261+
const environment = vite.createRunnableDevEnvironment('inline', config, {
262+
runnerOptions: {
263+
hmr: {
264+
logger: false,
265+
},
262266
},
267+
hot: false,
263268
});
264-
return { runner, server };
269+
await environment.init();
270+
271+
return environment;
265272
};
266273

267-
const requireDefaultExport = (path: string, mod: any) => {
274+
function requireDefaultExport(
275+
path: string,
276+
mod: any,
277+
): asserts mod is { default: unknown } {
268278
const relativePath = relative(wxtConfig.root, path);
269279
if (mod?.default == null) {
270280
const defineFn = relativePath.includes('.content')
@@ -277,36 +287,37 @@ export async function createViteBuilder(
277287
`${relativePath}: Default export not found, did you forget to call "export default ${defineFn}(...)"?`,
278288
);
279289
}
280-
};
290+
}
281291

282292
return {
283293
name: 'Vite',
284294
version: vite.version,
285295
async importEntrypoint(path) {
286-
const env = createExtensionEnvironment();
287-
const { runner, server } = await createViteNodeImporter([path]);
288-
const res = await env.run(() => runner.executeFile(path));
289-
await server.close();
290-
requireDefaultExport(path, res);
291-
return res.default;
296+
const [module] = await this.importEntrypoints([path]);
297+
298+
return module as any;
292299
},
293300
async importEntrypoints(paths) {
294-
const env = createExtensionEnvironment();
295-
const { runner, server } = await createViteNodeImporter(paths);
296-
const res = await env.run(() =>
297-
Promise.all(
298-
paths.map(async (path) => {
299-
const mod = await runner.executeFile(path);
300-
requireDefaultExport(path, mod);
301-
return mod.default;
302-
}),
303-
),
304-
);
305-
await server.close();
306-
return res;
301+
const context = createExtensionEnvironment();
302+
const environment = await createImporterEnvironment(paths);
303+
304+
try {
305+
return await context.run(
306+
async () =>
307+
await Promise.all(
308+
paths.map(async (path) => {
309+
const module = await environment.runner.import(path);
310+
requireDefaultExport(path, module);
311+
return module.default as any;
312+
}),
313+
),
314+
);
315+
} finally {
316+
await environment.close();
317+
}
307318
},
308319
async build(group) {
309-
let entryConfig;
320+
let entryConfig: vite.InlineConfig;
310321
if (Array.isArray(group)) entryConfig = getMultiPageConfig(group);
311322
else if (
312323
group.type === 'content-script-style' ||
@@ -315,12 +326,16 @@ export async function createViteBuilder(
315326
entryConfig = getCssConfig(group);
316327
else entryConfig = getLibModeConfig(group);
317328

318-
const buildConfig = vite.mergeConfig(await getBaseConfig(), entryConfig);
329+
const buildConfig: vite.InlineConfig = vite.mergeConfig(
330+
await getBaseConfig(),
331+
entryConfig,
332+
);
319333
await hooks.callHook(
320334
'vite:build:extendConfig',
321335
toArray(group),
322336
buildConfig,
323337
);
338+
324339
const result = await vite.build(buildConfig);
325340
const chunks = getBuildOutputChunks(result);
326341
return {

packages/wxt/src/core/builders/vite/plugins/removeEntrypointMainFunction.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function removeEntrypointMainFunction(
1919
handler(code, id) {
2020
if (id === absPath) {
2121
const newCode = removeMainFunctionCode(code);
22-
config.logger.debug('vite-node transformed entrypoint', path);
22+
config.logger.debug('transformed entrypoint', path);
2323
config.logger.debug(`Original:\n---\n${code}\n---`);
2424
config.logger.debug(`Transformed:\n---\n${newCode.code}\n---`);
2525
return newCode;

packages/wxt/src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1029,7 +1029,7 @@ export interface WxtBuilder {
10291029
/**
10301030
* Import a JS entrypoint file, returning the default export containing the options.
10311031
*/
1032-
importEntrypoint<T>(path: string): Promise<T>;
1032+
importEntrypoint<T>(this: WxtBuilder, path: string): Promise<T>;
10331033
/**
10341034
* Import a list of JS entrypoint files, returning their options.
10351035
*/

pnpm-lock.yaml

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)