@nullvoxpopuli/ember-vite 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ Then:
35
35
  ## Requirements
36
36
 
37
37
  - `type=module` in your ember app
38
- - babel config must be named `babel.config.js`
38
+ - babel config must be named `babel.config.js`, or passed as `babel.configFile`
39
39
  - `@embroider/vite` is up to date~ish
40
40
 
41
41
  ## Configuration
@@ -61,4 +61,8 @@ ember({
61
61
 
62
62
  Each option is documented on its type.
63
63
 
64
- If the project depends on `ember-concurrency`, `ember-intl`, `ember-scoped-css` or `unplugin-icons`, babel compiles their modules with no option.
64
+ What this plugin sets in `build`, `build.rolldownOptions.output` and `build.rolldownOptions.optimization`
65
+ are defaults: a setting there in your own vite config wins,
66
+ for example `build.sourcemap: "hidden"` or `build.rolldownOptions.output.strictExecutionOrder: false`.
67
+
68
+ If the project depends on `ember-concurrency`, `ember-intl`, `ember-qunit-nice-errors`, `ember-scoped-css` or `unplugin-icons`, babel compiles their modules with no option.
package/dist/index.js CHANGED
@@ -134,6 +134,23 @@ function defaultBabelPlugins(mode) {
134
134
  ];
135
135
  }
136
136
  /**
137
+ * Other names babel loads a project config from.
138
+ */
139
+ const OTHER_BABEL_CONFIGS = [
140
+ "babel.config.mjs",
141
+ "babel.config.cjs",
142
+ "babel.config.cts",
143
+ "babel.config.json"
144
+ ];
145
+ /**
146
+ * A v2 addon. Its babel config is for publishing, so vite keeps the default plugins.
147
+ */
148
+ function isLibrary() {
149
+ const manifestPath = join(process.cwd(), "package.json");
150
+ if (!existsSync(manifestPath)) return false;
151
+ return JSON.parse(readFileSync(manifestPath, "utf-8"))["ember-addon"]?.type === "addon";
152
+ }
153
+ /**
137
154
  * The project's babel config wins when it exists.
138
155
  * `babel.configFile` selects which one (e.g. a test-only `config/test/babel.config.js`).
139
156
  *
@@ -141,10 +158,17 @@ function defaultBabelPlugins(mode) {
141
158
  * so no config file is required.
142
159
  * Babel helpers are inlined in that case:
143
160
  * projects without a babel config don't carry `@babel/runtime`.
161
+ *
162
+ * An app whose config has another name would otherwise get the defaults without noticing,
163
+ * so that is an error.
144
164
  */
145
165
  function babelOptions(nvpConfig) {
146
166
  const configFile = resolve(join(process.cwd(), nvpConfig.babel?.configFile ?? "./babel.config.js"));
147
167
  if (existsSync(configFile)) return { configFile };
168
+ if (!nvpConfig.babel?.configFile && !isLibrary()) {
169
+ const otherConfig = OTHER_BABEL_CONFIGS.find((name) => existsSync(join(process.cwd(), name)));
170
+ if (otherConfig) throw new Error(`@nullvoxpopuli/ember-vite reads babel.config.js, but this project has ${otherConfig}. Pass \`ember({ babel: { configFile: "./${otherConfig}" } })\` to use it.`);
171
+ }
148
172
  /**
149
173
  * The config hook fills this list, once it knows the vite mode.
150
174
  * The babel plugins keep a reference to it, so they see the filled list.
@@ -161,6 +185,7 @@ function babelOptions(nvpConfig) {
161
185
  *
162
186
  * - ember-concurrency's decorators
163
187
  * - ember-intl's formatMessage macro
188
+ * - ember-qunit-nice-errors, which adds a message to each QUnit assertion
164
189
  * - ember-scoped-css transforms
165
190
  * - unplugin-icons, whose icon modules compile with `template()`.
166
191
  * Their ids have no file extension, so only the id matches them.
@@ -171,6 +196,7 @@ const LIBRARY_FILTERS = {
171
196
  imports: ["ember-intl/helpers/format-message"],
172
197
  code: [/\bintl\.formatMessage\b/]
173
198
  },
199
+ "ember-qunit-nice-errors": { code: [/\bassert\.[a-zA-Z]+\(/] },
174
200
  "ember-scoped-css": { imports: ["ember-scoped-css"] },
175
201
  "unplugin-icons": { ids: [/^~icons\//] }
176
202
  };
@@ -214,6 +240,11 @@ function ember(nvpConfig = {}) {
214
240
  {
215
241
  name: "ember:nullvoxpopuli",
216
242
  async config(viteConfig, env) {
243
+ /**
244
+ * Read before the config hooks below write their defaults into `viteConfig`,
245
+ * and put back over them after `applyConfig`.
246
+ */
247
+ const project = projectConfig(viteConfig);
217
248
  /**
218
249
  * The hook reads the rolldown version from the plugin context,
219
250
  * and takes its esbuild path without it.
@@ -237,7 +268,9 @@ function ember(nvpConfig = {}) {
237
268
  viteConfig.optimizeDeps.rolldownOptions ||= {};
238
269
  viteConfig.optimizeDeps.rolldownOptions.tsconfig = true;
239
270
  applyConfig(viteConfig, env, nvpConfig);
271
+ keepProjectConfig(viteConfig, project);
240
272
  viteConfig.optimizeDeps.rolldownOptions.plugins = [
273
+ ...project.optimizeDepsPlugins,
241
274
  resolver({ rolldown: true }),
242
275
  templateTag(),
243
276
  maybeBabel$1({
@@ -259,6 +292,43 @@ function ember(nvpConfig = {}) {
259
292
  ];
260
293
  }
261
294
  /**
295
+ * What the project's own vite config sets, before any config hook changes it.
296
+ *
297
+ * What the config hooks here and in `@embroider/vite` set in `build`,
298
+ * `build.rolldownOptions.output` and `build.rolldownOptions.optimization` are defaults:
299
+ * a project that sets one, such as `build.sourcemap: "hidden"`
300
+ * or `build.rolldownOptions.output.strictExecutionOrder: false`, keeps its value.
301
+ * The project's own optimizeDeps plugins run before the ones this plugin adds.
302
+ */
303
+ function projectConfig(viteConfig) {
304
+ const build = viteConfig.build ?? {};
305
+ const output = build.rolldownOptions?.output;
306
+ const optimizeDepsPlugins = viteConfig.optimizeDeps?.rolldownOptions?.plugins;
307
+ return {
308
+ /**
309
+ * Vite 8 makes `build.rollupOptions` an accessor for `build.rolldownOptions`.
310
+ * Neither is put back: that would replace the object the config hooks fill in.
311
+ */
312
+ build: setValues(build, ["rolldownOptions", "rollupOptions"]),
313
+ output: Array.isArray(output) ? {} : setValues(output),
314
+ optimization: setValues(build.rolldownOptions?.optimization),
315
+ optimizeDepsPlugins: Array.isArray(optimizeDepsPlugins) ? [...optimizeDepsPlugins] : []
316
+ };
317
+ }
318
+ /**
319
+ * The entries that have a value.
320
+ * A project that sets `sourcemap: undefined` gets the default, as if it had not set it.
321
+ */
322
+ function setValues(object, skip = []) {
323
+ return Object.fromEntries(Object.entries(object ?? {}).filter(([key, value]) => value !== void 0 && !skip.includes(key)));
324
+ }
325
+ function keepProjectConfig(viteConfig, project) {
326
+ Object.assign(viteConfig.build, project.build);
327
+ const { output, optimization } = viteConfig.build.rolldownOptions ?? {};
328
+ if (output && !Array.isArray(output)) Object.assign(output, project.output);
329
+ if (optimization) Object.assign(optimization, project.optimization);
330
+ }
331
+ /**
262
332
  * `vite preview` serves the build on `$PORT`, the port that hosts and CI give,
263
333
  * or on 4200, the port of the dev server.
264
334
  * Vite itself reads no `$PORT`, and `@embroider/vite` only sets the dev server's port.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-vite",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Meta plugin for ember projects focusing on speed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/src/ember.test.ts CHANGED
@@ -3,7 +3,7 @@ import { interpreter, type TopLevelFilterExpression } from "@rolldown/pluginutil
3
3
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import type { ConfigEnv, ConfigPluginContext, Plugin } from "vite";
6
+ import { resolveConfig, type ConfigEnv, type ConfigPluginContext, type Plugin } from "vite";
7
7
  import { afterEach, describe, expect, it } from "vitest";
8
8
 
9
9
  import { ember } from "./ember.ts";
@@ -76,6 +76,96 @@ describe("ember", () => {
76
76
  });
77
77
  });
78
78
 
79
+ describe("the project's own vite config", () => {
80
+ it("keeps the project's build settings, and the defaults fill in the rest", async () => {
81
+ const config = await configure(
82
+ { command: "build", mode: "production" },
83
+ {
84
+ build: {
85
+ sourcemap: "hidden",
86
+ rolldownOptions: { output: { strictExecutionOrder: false } },
87
+ },
88
+ },
89
+ );
90
+
91
+ expect(config.build.sourcemap).toBe("hidden");
92
+ expect(config.build.rolldownOptions.output.strictExecutionOrder).toBe(false);
93
+ // Not the terser that @embroider/vite picks when the project sets no minifier.
94
+ expect(config.build.minify).toBe("oxc");
95
+ expect(config.build.rolldownOptions.output.minify).toBe(true);
96
+ });
97
+
98
+ it("keeps the project's build settings in development mode", async () => {
99
+ const config = await configure(
100
+ { command: "build", mode: "development" },
101
+ { build: { sourcemap: false, rolldownOptions: { output: { codeSplitting: false } } } },
102
+ );
103
+
104
+ expect(config.build.sourcemap).toBe(false);
105
+ expect(config.build.rolldownOptions.output.codeSplitting).toBe(false);
106
+ expect(config.build.minify).toBe(false);
107
+ });
108
+
109
+ it("keeps the project's optimization settings", async () => {
110
+ const config = await configure(
111
+ { command: "build", mode: "production" },
112
+ { build: { rolldownOptions: { optimization: { pifeForModuleWrappers: false } } } },
113
+ );
114
+
115
+ expect(config.build.rolldownOptions.optimization.pifeForModuleWrappers).toBe(false);
116
+ expect(config.build.rolldownOptions.optimization.inlineConst).toEqual({
117
+ mode: "smart",
118
+ pass: 3,
119
+ });
120
+ });
121
+
122
+ it("uses the default for a setting the project leaves undefined", async () => {
123
+ const config = await configure(
124
+ { command: "build", mode: "production" },
125
+ { build: { sourcemap: undefined } },
126
+ );
127
+
128
+ expect(config.build.sourcemap).toBe(true);
129
+ });
130
+
131
+ /**
132
+ * Vite gives the config hooks a `build.rollupOptions` accessor for `build.rolldownOptions`,
133
+ * which the plain objects of `configure()` don't have.
134
+ */
135
+ it("keeps what the config hooks put in build.rolldownOptions, through vite", async () => {
136
+ const config = await resolveConfig(
137
+ {
138
+ configFile: false,
139
+ logLevel: "silent",
140
+ plugins: [ember()],
141
+ build: { sourcemap: "hidden" },
142
+ },
143
+ "build",
144
+ "production",
145
+ );
146
+
147
+ expect(config.build.sourcemap).toBe("hidden");
148
+ expect(config.build.rolldownOptions.moduleTypes).toEqual({ ".ts": "js" });
149
+ expect(config.build.rolldownOptions.output).toMatchObject({ strictExecutionOrder: true });
150
+ });
151
+
152
+ it("runs the project's optimizeDeps plugins before its own", async () => {
153
+ const config = await configure(
154
+ { command: "serve", mode: "development" },
155
+ { optimizeDeps: { rolldownOptions: { plugins: [{ name: "project-plugin" }] } } },
156
+ );
157
+
158
+ expect(
159
+ config.optimizeDeps.rolldownOptions.plugins.map((plugin: Plugin) => plugin.name),
160
+ ).toEqual([
161
+ "project-plugin",
162
+ "embroider-resolver",
163
+ "embroider-template-tag",
164
+ "nullvoxpopuli:babel",
165
+ ]);
166
+ });
167
+ });
168
+
79
169
  /**
80
170
  * This package has no babel config,
81
171
  * so `ember()` uses its default babel plugins,
@@ -175,6 +265,7 @@ function inProjectWithLibraries() {
175
265
  const devDependencies = {
176
266
  "ember-concurrency": "*",
177
267
  "ember-intl": "*",
268
+ "ember-qunit-nice-errors": "*",
178
269
  "ember-scoped-css": "*",
179
270
  "unplugin-icons": "*",
180
271
  };
@@ -225,6 +316,73 @@ describe("babel config file", () => {
225
316
  // @ts-expect-error the babel plugin has function hooks
226
317
  expect(babel.applyToEnvironment.call(CONTEXT, { name: "client" })).toBe(true);
227
318
  });
319
+
320
+ it.each(["babel.config.mjs", "babel.config.cjs", "babel.config.cts", "babel.config.json"])(
321
+ "says how to use %s instead of ignoring it",
322
+ (name) => {
323
+ inProject({ "package.json": `{ "type": "module" }`, [name]: "{}" });
324
+
325
+ expect(() => ember()).toThrow(
326
+ `@nullvoxpopuli/ember-vite reads babel.config.js, but this project has ${name}. ` +
327
+ `Pass \`ember({ babel: { configFile: "./${name}" } })\` to use it.`,
328
+ );
329
+ },
330
+ );
331
+
332
+ it("keeps the default plugins for a library, whose babel config is for publishing", () => {
333
+ inProject({
334
+ "package.json": `{ "type": "module", "ember-addon": { "version": 2, "type": "addon" } }`,
335
+ "babel.config.cjs": "module.exports = {};",
336
+ });
337
+
338
+ expect(() => ember()).not.toThrow();
339
+ });
340
+
341
+ it("uses babel.config.js when another config sits next to it", () => {
342
+ inProject({
343
+ "package.json": `{ "type": "module" }`,
344
+ "babel.config.js": "export default { plugins: [] };",
345
+ "babel.config.cjs": "module.exports = {};",
346
+ });
347
+
348
+ expect(() => ember()).not.toThrow();
349
+ });
350
+
351
+ const MARKER_PLUGIN = [
352
+ `export default ({ types: t }) => ({`,
353
+ ` visitor: {`,
354
+ ` Program(path) {`,
355
+ ` path.unshiftContainer("body", t.expressionStatement(t.stringLiteral("from the config file")));`,
356
+ ` },`,
357
+ ` },`,
358
+ `});`,
359
+ ].join("\n");
360
+
361
+ it("uses the config that babel.configFile names", async () => {
362
+ const directory = inProject({
363
+ "package.json": `{ "type": "module" }`,
364
+ "marker-plugin.js": MARKER_PLUGIN,
365
+ "babel.config.mjs": `export default { plugins: ["./marker-plugin.js"] };`,
366
+ });
367
+
368
+ const babel = await startedBabel(
369
+ ember({ babel: { configFile: "./babel.config.mjs" } }) as Plugin[],
370
+ );
371
+
372
+ try {
373
+ // @ts-expect-error the babel plugin has an object transform hook
374
+ const result = await babel.transform.handler.call(
375
+ CONTEXT,
376
+ `import { macroCondition } from "@embroider/macros";`,
377
+ join(directory, "app/a.js"),
378
+ );
379
+
380
+ expect(result.code).toContain("from the config file");
381
+ } finally {
382
+ // @ts-expect-error the babel plugin ends its workers in closeBundle
383
+ await babel.closeBundle.call({ meta: { watchMode: false } });
384
+ }
385
+ });
228
386
  });
229
387
 
230
388
  describe("babel filter in the dev server", () => {
@@ -417,6 +575,11 @@ describe("libraries that need babel", () => {
417
575
  `export const title = this.intl.formatMessage("Hello");`,
418
576
  "/app/components/a.js",
419
577
  ),
578
+ "ember-qunit-nice-errors": interpreter(
579
+ filter,
580
+ `test("it works", (assert) => assert.ok(true));`,
581
+ "/tests/unit/a-test.js",
582
+ ),
420
583
  "ember-scoped-css": interpreter(
421
584
  filter,
422
585
  `import { scopedClass } from "ember-scoped-css";`,
@@ -434,6 +597,7 @@ describe("libraries that need babel", () => {
434
597
  "ember-concurrency": false,
435
598
  "ember-intl formatMessage": false,
436
599
  "ember-intl import": false,
600
+ "ember-qunit-nice-errors": false,
437
601
  "ember-scoped-css": false,
438
602
  "unplugin-icons": false,
439
603
  }
@@ -448,6 +612,7 @@ describe("libraries that need babel", () => {
448
612
  "ember-concurrency": true,
449
613
  "ember-intl formatMessage": true,
450
614
  "ember-intl import": true,
615
+ "ember-qunit-nice-errors": true,
451
616
  "ember-scoped-css": true,
452
617
  "unplugin-icons": true,
453
618
  }
package/src/ember.ts CHANGED
@@ -97,6 +97,27 @@ type BabelOptions =
97
97
  plugins: ReturnType<typeof defaultBabelPlugins>;
98
98
  };
99
99
 
100
+ /**
101
+ * Other names babel loads a project config from.
102
+ */
103
+ const OTHER_BABEL_CONFIGS = [
104
+ "babel.config.mjs",
105
+ "babel.config.cjs",
106
+ "babel.config.cts",
107
+ "babel.config.json",
108
+ ];
109
+
110
+ /**
111
+ * A v2 addon. Its babel config is for publishing, so vite keeps the default plugins.
112
+ */
113
+ function isLibrary(): boolean {
114
+ const manifestPath = join(process.cwd(), "package.json");
115
+
116
+ if (!existsSync(manifestPath)) return false;
117
+
118
+ return JSON.parse(readFileSync(manifestPath, "utf-8"))["ember-addon"]?.type === "addon";
119
+ }
120
+
100
121
  /**
101
122
  * The project's babel config wins when it exists.
102
123
  * `babel.configFile` selects which one (e.g. a test-only `config/test/babel.config.js`).
@@ -105,6 +126,9 @@ type BabelOptions =
105
126
  * so no config file is required.
106
127
  * Babel helpers are inlined in that case:
107
128
  * projects without a babel config don't carry `@babel/runtime`.
129
+ *
130
+ * An app whose config has another name would otherwise get the defaults without noticing,
131
+ * so that is an error.
108
132
  */
109
133
  function babelOptions(nvpConfig: Config): BabelOptions {
110
134
  const configFile = resolve(
@@ -115,6 +139,17 @@ function babelOptions(nvpConfig: Config): BabelOptions {
115
139
  return { configFile };
116
140
  }
117
141
 
142
+ if (!nvpConfig.babel?.configFile && !isLibrary()) {
143
+ const otherConfig = OTHER_BABEL_CONFIGS.find((name) => existsSync(join(process.cwd(), name)));
144
+
145
+ if (otherConfig) {
146
+ throw new Error(
147
+ `@nullvoxpopuli/ember-vite reads babel.config.js, but this project has ${otherConfig}. ` +
148
+ `Pass \`ember({ babel: { configFile: "./${otherConfig}" } })\` to use it.`,
149
+ );
150
+ }
151
+ }
152
+
118
153
  /**
119
154
  * The config hook fills this list, once it knows the vite mode.
120
155
  * The babel plugins keep a reference to it, so they see the filled list.
@@ -132,6 +167,7 @@ function babelOptions(nvpConfig: Config): BabelOptions {
132
167
  *
133
168
  * - ember-concurrency's decorators
134
169
  * - ember-intl's formatMessage macro
170
+ * - ember-qunit-nice-errors, which adds a message to each QUnit assertion
135
171
  * - ember-scoped-css transforms
136
172
  * - unplugin-icons, whose icon modules compile with `template()`.
137
173
  * Their ids have no file extension, so only the id matches them.
@@ -145,6 +181,7 @@ const LIBRARY_FILTERS: Record<
145
181
  imports: ["ember-intl/helpers/format-message"],
146
182
  code: [/\bintl\.formatMessage\b/],
147
183
  },
184
+ "ember-qunit-nice-errors": { code: [/\bassert\.[a-zA-Z]+\(/] },
148
185
  "ember-scoped-css": { imports: ["ember-scoped-css"] },
149
186
  "unplugin-icons": { ids: [/^~icons\//] },
150
187
  };
@@ -271,6 +308,12 @@ export function ember(nvpConfig: Config = {}) {
271
308
  // no compat
272
309
  name: "ember:nullvoxpopuli",
273
310
  async config(this: ConfigPluginContext, viteConfig: any, env: ConfigEnv) {
311
+ /**
312
+ * Read before the config hooks below write their defaults into `viteConfig`,
313
+ * and put back over them after `applyConfig`.
314
+ */
315
+ const project = projectConfig(viteConfig);
316
+
274
317
  /**
275
318
  * The hook reads the rolldown version from the plugin context,
276
319
  * and takes its esbuild path without it.
@@ -309,8 +352,10 @@ export function ember(nvpConfig: Config = {}) {
309
352
  viteConfig.optimizeDeps.rolldownOptions.tsconfig = true;
310
353
 
311
354
  applyConfig(viteConfig, env, nvpConfig);
355
+ keepProjectConfig(viteConfig, project);
312
356
 
313
357
  viteConfig.optimizeDeps.rolldownOptions.plugins = [
358
+ ...project.optimizeDepsPlugins,
314
359
  resolver({ rolldown: true }),
315
360
  templateTag(),
316
361
 
@@ -335,6 +380,53 @@ export function ember(nvpConfig: Config = {}) {
335
380
  ];
336
381
  }
337
382
 
383
+ /**
384
+ * What the project's own vite config sets, before any config hook changes it.
385
+ *
386
+ * What the config hooks here and in `@embroider/vite` set in `build`,
387
+ * `build.rolldownOptions.output` and `build.rolldownOptions.optimization` are defaults:
388
+ * a project that sets one, such as `build.sourcemap: "hidden"`
389
+ * or `build.rolldownOptions.output.strictExecutionOrder: false`, keeps its value.
390
+ * The project's own optimizeDeps plugins run before the ones this plugin adds.
391
+ */
392
+ function projectConfig(viteConfig: UserConfig) {
393
+ const build = viteConfig.build ?? {};
394
+ const output = build.rolldownOptions?.output;
395
+ const optimizeDepsPlugins = viteConfig.optimizeDeps?.rolldownOptions?.plugins;
396
+
397
+ return {
398
+ /**
399
+ * Vite 8 makes `build.rollupOptions` an accessor for `build.rolldownOptions`.
400
+ * Neither is put back: that would replace the object the config hooks fill in.
401
+ */
402
+ build: setValues(build, ["rolldownOptions", "rollupOptions"]),
403
+ output: Array.isArray(output) ? {} : setValues(output),
404
+ optimization: setValues(build.rolldownOptions?.optimization),
405
+ optimizeDepsPlugins: Array.isArray(optimizeDepsPlugins) ? [...optimizeDepsPlugins] : [],
406
+ };
407
+ }
408
+
409
+ /**
410
+ * The entries that have a value.
411
+ * A project that sets `sourcemap: undefined` gets the default, as if it had not set it.
412
+ */
413
+ function setValues(object: object | undefined, skip: string[] = []) {
414
+ return Object.fromEntries(
415
+ Object.entries(object ?? {}).filter(
416
+ ([key, value]) => value !== undefined && !skip.includes(key),
417
+ ),
418
+ );
419
+ }
420
+
421
+ function keepProjectConfig(viteConfig: UserConfig, project: ReturnType<typeof projectConfig>) {
422
+ Object.assign(viteConfig.build!, project.build);
423
+
424
+ const { output, optimization } = viteConfig.build!.rolldownOptions ?? {};
425
+
426
+ if (output && !Array.isArray(output)) Object.assign(output, project.output);
427
+ if (optimization) Object.assign(optimization, project.optimization);
428
+ }
429
+
338
430
  /**
339
431
  * `vite preview` serves the build on `$PORT`, the port that hosts and CI give,
340
432
  * or on 4200, the port of the dev server.