Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/vite/configuration/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,9 +346,8 @@ export const baseConfig = ({ mode, flavor }: { mode: string; flavor?: string }):
plugins: [
// Must stay first: Vite stubs `node:` builtins for the browser otherwise.
nativescriptBuiltinModules(),
// Merge any dependency-provided `nativescript.vite.mjs` configs. Runs
// in an awaited `config` hook so ESM configs load correctly.
externalConfigsPlugin(),
// Apply any dependency-provided `nativescript.vite.mjs` configs.
...externalConfigsPlugin(),
// Under HMR, rewrite every bare `@nativescript/core*` specifier to
// the full /ns/core HTTP URL so bundle.mjs contains NO bundled copy
// of the core runtime (see helpers/ns-core-external-urls.ts).
Expand Down
46 changes: 39 additions & 7 deletions packages/vite/helpers/external-configs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,31 @@ import { describe, it, expect, vi } from 'vitest';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { resolveConfig, type Plugin } from 'vite';

// Fixture dependency shipping an ESM `nativescript.vite.mjs` that uses a
// top-level await. `require()` (even Node's require-of-ESM) cannot load a module
// with top-level await, so this exercises the async `import()` fallback — the
// path that previously deferred into a never-awaited array and was dropped.
// with top-level await, so this exercises the async `import()` fallback.
const depDir = mkdtempSync(path.join(tmpdir(), 'ns-ext-cfg-'));
writeFileSync(path.join(depDir, 'nativescript.vite.mjs'), `await Promise.resolve();\nexport default () => ({ define: { __EXTERNAL_ESM_OK__: '"true"' } });\n`);
writeFileSync(
path.join(depDir, 'nativescript.vite.mjs'),
`await Promise.resolve();
export default () => {
globalThis.__nsExternalConfigCalls = (globalThis.__nsExternalConfigCalls ?? 0) + 1;
return {
define: { __EXTERNAL_ESM_OK__: '"true"' },
plugins: [
{
name: 'fixture-external-plugin',
configResolved() {
globalThis.__nsExternalPluginRan = true;
},
},
],
};
};
`,
);

vi.mock('./utils.js', () => ({
getAllDependencies: () => ['fixture-dep'],
Expand All @@ -17,11 +35,25 @@ vi.mock('./utils.js', () => ({

import { externalConfigsPlugin } from './external-configs.js';

const globals = globalThis as { __nsExternalConfigCalls?: number; __nsExternalPluginRan?: boolean };

describe('externalConfigsPlugin', () => {
it('applies an ESM (top-level-await) external config via the awaited config hook', async () => {
const plugin = externalConfigsPlugin();
const hook = plugin.config as (config: unknown, env: unknown) => unknown;
const result = (await hook.call(plugin, {}, { command: 'serve', mode: 'development' })) as { define?: Record<string, unknown> } | undefined;
it('merges an ESM (top-level-await) external config via the awaited config hook, without its plugins', async () => {
const plugin = externalConfigsPlugin().find((entry): entry is Plugin => (entry as Plugin)?.name === 'ns-external-configs');
const hook = plugin!.config as (config: unknown, env: unknown) => unknown;
const result = (await hook.call(plugin, {}, { command: 'serve', mode: 'development' })) as Record<string, any> | undefined;
expect(result?.define?.__EXTERNAL_ESM_OK__).toBe('"true"');
expect(result).not.toHaveProperty('plugins');
});

it('registers plugins returned by an external config with Vite', async () => {
const resolved = await resolveConfig({ configFile: false, root: depDir, logLevel: 'silent', plugins: externalConfigsPlugin() }, 'serve');
expect(resolved.plugins.map((p) => p.name)).toContain('fixture-external-plugin');
expect(globals.__nsExternalPluginRan).toBe(true);
expect(resolved.define?.__EXTERNAL_ESM_OK__).toBe('"true"');
});

it('loads each external config once per process', () => {
expect(globals.__nsExternalConfigCalls).toBe(1);
});
});
45 changes: 32 additions & 13 deletions packages/vite/helpers/external-configs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Plugin, UserConfig } from 'vite';
import type { Plugin, PluginOption, UserConfig } from 'vite';
import { mergeConfig } from 'vite';
import path from 'path';
import fs from 'fs';
Expand Down Expand Up @@ -62,26 +62,45 @@ async function collectExternalConfigs(): Promise<UserConfig[]> {
return merges;
}

function loadExternalConfigs(): Promise<UserConfig[]> {
cached ??= collectExternalConfigs();
return cached;
}

/**
* Vite plugin that merges every dependency's optional `nativescript.vite.mjs`
* config into the build.
* Vite plugins that apply every dependency's optional `nativescript.vite.mjs`
* config to the build.
*
* Discovery runs only once Vite resolves the config — which it awaits — rather
* than synchronously while assembling the base config. That is what lets ESM
* configs (including ones using top-level await, which can't be `require()`d)
* load via `import()` and still apply, without forcing the config factory or
* any app's `vite.config.ts` to become async.
*
* Discovery runs in the plugin's `config` hook — which Vite awaits — rather than
* synchronously while assembling the base config. That is what lets ESM configs
* (including ones using top-level await, which can't be `require()`d) load via
* `import()` and still apply, without forcing the config factory or any app's
* `vite.config.ts` to become async.
* Vite ignores `plugins` returned from a `config` hook, so each config's
* `plugins` are contributed through a thenable entry that Vite flattens into
* the plugin list; everything else is merged by the `config` hook.
*/
export function externalConfigsPlugin(): Plugin {
return {
export function externalConfigsPlugin(): PluginOption[] {
const configPlugin: Plugin = {
name: 'ns-external-configs',
async config() {
cached ??= collectExternalConfigs();
const merges = await cached;
const merges = await loadExternalConfigs();
if (!merges.length) {
return undefined;
}
return merges.reduce<UserConfig>((acc, config) => mergeConfig(acc, config), {});
return merges.reduce<UserConfig>((acc, { plugins: _plugins, ...config }) => mergeConfig(acc, config), {});
},
};

// Vite only calls `.then` on plugin entries, so a thenable keeps discovery
// lazy instead of starting it whenever the base config is built.
const externalPlugins: PromiseLike<PluginOption[]> = {
then: (onfulfilled, onrejected) =>
loadExternalConfigs()
.then((configs) => configs.map((config) => config.plugins ?? []))
.then(onfulfilled, onrejected),
};

return [configPlugin, externalPlugins as Promise<PluginOption[]>];
}
Loading