@nullvoxpopuli/ember-vite 1.0.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 ADDED
@@ -0,0 +1,70 @@
1
+ # `@nullvoxpopuli/ember-vite`
2
+
3
+ A speed-optimized default meta-config for ember projects.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm add @nullvoxpopuli/ember-vite
9
+ ```
10
+
11
+ Requires node 24+
12
+
13
+ ## Usage
14
+
15
+ in your vite config
16
+
17
+ ```js
18
+ import { defineConfig } from "vite";
19
+ import { ember } from "@nullvoxpopuli/ember-vite";
20
+
21
+ export default defineConfig({
22
+ plugins: [
23
+ ember(),
24
+ ],
25
+ }
26
+ ```
27
+
28
+ And remove any plugins from embroider or babel.
29
+ Then delete from your package.json: `@rollup/plugin-babel`, `@embroider/core`, `@embroider/vite`.
30
+
31
+ > [!NOTE]
32
+ > babel related deps are still needed for linting, so don't delete those
33
+
34
+ ## Configuration
35
+
36
+ The `ember()` plugin takes the following options:
37
+
38
+ ```ts
39
+ ember({
40
+ // optional production configs
41
+ production: {
42
+ // optional configuration of codeSplitting.groups
43
+ // in the vite config.
44
+ //
45
+ // Docs here:
46
+ // https://rolldown.rs/reference/OutputOptions.codeSplitting#groups
47
+ codeSplittingGroups: [
48
+ /* ... */
49
+ ],
50
+ },
51
+ // optional babel config
52
+ babel: {
53
+ // defaults to true.
54
+ // when babel runs, do so in parallel across many cores.
55
+ parallel: false,
56
+ // optional way to configure when babel is activateed.
57
+ // by default, all transforming is oxc, except when babel is needed
58
+ // (for things not currently implemented in oxc)
59
+ include: {
60
+ // if a file imports from anything in this array, use babel instead of
61
+ // oxc for that file.
62
+ //
63
+ // For example: ['ember-concurrency', 'ember-intl/format-message'],
64
+ whenImporting: [
65
+ /* ... */
66
+ ],
67
+ },
68
+ },
69
+ });
70
+ ```
package/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { ember } from "./src/ember.ts";
2
+ export { maybeBabel } from "./src/maybe-babel.ts";
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@nullvoxpopuli/ember-vite",
3
+ "version": "1.0.0",
4
+ "description": "Meta plugin for ember projects focusing on speed.",
5
+ "type": "module",
6
+ "main": "index.ts",
7
+ "keywords": [
8
+ "vite",
9
+ "ember",
10
+ "meta plugin"
11
+ ],
12
+ "author": "NullVoxPopuli",
13
+ "license": "MIT",
14
+ "packageManager": "pnpm@10.28.0",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "dependencies": {
19
+ "@babel/core": "^7.28.6",
20
+ "@embroider/core": "^4.4.2",
21
+ "@embroider/vite": "^1.5.0",
22
+ "@rollup/plugin-babel": "^6.1.0",
23
+ "oxc-parser": "^0.132.0",
24
+ "oxc-transform": "^0.132.0",
25
+ "zimmerframe": "^1.1.4"
26
+ },
27
+ "engines": {
28
+ "node": ">= 24"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.9.3",
32
+ "vite": "^8.0.14"
33
+ }
34
+ }
package/src/ember.ts ADDED
@@ -0,0 +1,239 @@
1
+ import { ember as embroiderEmber, extensions, resolver, templateTag } from "@embroider/vite";
2
+ import { existsSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import type { ConfigEnv, ResolvedConfig } from "vite";
5
+
6
+ import { maybeBabel } from "./maybe-babel.ts";
7
+
8
+ const emberConfig = embroiderEmber()[3]!;
9
+
10
+ const cwd = process.cwd();
11
+ function absolutePath(relativePath: string) {
12
+ return join(cwd, relativePath);
13
+ }
14
+
15
+ interface Config {
16
+ babel?: {
17
+ /**
18
+ * defaults to true.
19
+ * when babel runs, do so in parallel across many cores.
20
+ */
21
+ parallel?: false;
22
+
23
+ /**
24
+ * optional way to configure when babel is activateed.
25
+ * by default, all transforming is oxc, except when babel is needed
26
+ * (for things not currently implemented in oxc)
27
+ */
28
+ include?: {
29
+ /**
30
+ * if a file imports from anything in this array, use babel instead of
31
+ * oxc for that file.
32
+ *
33
+ * For example: ['ember-concurrency'],
34
+ */
35
+ whenImporting?: (string | "ember-concurrency" | "ember-scoped-css")[];
36
+ };
37
+ };
38
+ /**
39
+ * optional production configs
40
+ */
41
+ production?: {
42
+ /**
43
+ * optional configuration of codeSplitting.groups
44
+ * in the vite config.
45
+ *
46
+ * Docs here:
47
+ * https://rolldown.rs/reference/OutputOptions.codeSplitting#groups
48
+ */
49
+ codeSplittingGroups: any[];
50
+ };
51
+ }
52
+
53
+ export function ember(nvpConfig: Config) {
54
+ const babelConfigFile = resolve(join(process.cwd(), "./babel.config.mjs"));
55
+ const defaultEnv = { mode: process.env.NODE_ENV || "development" };
56
+
57
+ /*
58
+ * Plugins must be returned as top-level array entries — NOT pushed into
59
+ * config.plugins inside a config() hook. Vite 8 extracts user plugins
60
+ * *before* config hooks run, so anything added later is invisible to the
61
+ * plugin container (resolveId, load, etc. hooks never fire).
62
+ */
63
+ return [
64
+ {
65
+ // no compat
66
+ name: "ember:nullvoxpopuli",
67
+ async config(viteConfig: any, env: ConfigEnv) {
68
+ // @ts-expect-error it exists
69
+ await emberConfig.config(viteConfig, env);
70
+
71
+ viteConfig.experimental ||= {};
72
+ viteConfig.build ||= {};
73
+ viteConfig.optimizeDeps ||= {};
74
+
75
+ viteConfig.oxc = {
76
+ // babel handles legacy decorators
77
+ // decorator: {
78
+ // legacy: true,
79
+ // },
80
+ };
81
+ // config.experimental.bundledDev = true;
82
+ viteConfig.experimental.nativeMagicString = true;
83
+ delete viteConfig.esbuild;
84
+ delete viteConfig.optimizeDeps.esbuildOptions;
85
+
86
+ viteConfig.build.reportCompressedSize = false;
87
+ viteConfig.build.extensions = extensions;
88
+ viteConfig.optimizeDeps.extensions = [".gjs", ".gts"];
89
+ viteConfig.optimizeDeps.rolldownOptions ||= {};
90
+ viteConfig.optimizeDeps.rolldownOptions.tsconfig = true;
91
+
92
+ applyConfig(viteConfig, env, nvpConfig);
93
+
94
+ viteConfig.optimizeDeps.rolldownOptions.plugins = [
95
+ resolver({ rolldown: true }),
96
+ templateTag(),
97
+
98
+ // Libraries will have precompileTemplate and macros, etc,
99
+ // and we need to compile that away using this app's
100
+ // template compiler
101
+ maybeBabel({ env, parallel: nvpConfig.babel?.parallel, configFile: babelConfigFile }),
102
+ ];
103
+ },
104
+ },
105
+ resolver({ rolldown: true }),
106
+ templateTag(),
107
+ maybeBabel({
108
+ env: defaultEnv,
109
+ parallel: nvpConfig.babel?.parallel,
110
+ configFile: babelConfigFile,
111
+ }),
112
+ ];
113
+ }
114
+
115
+ const MODE_DEV = "development";
116
+
117
+ function isDev(mode) {
118
+ return mode === MODE_DEV;
119
+ }
120
+
121
+ function applyConfig(viteConfig: ResolvedConfig, env, nvpConfig: Config) {
122
+ if (isDev(env.mode)) {
123
+ return dev(viteConfig, nvpConfig);
124
+ }
125
+
126
+ return prod(viteConfig, nvpConfig);
127
+ }
128
+
129
+ function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
130
+ /**************************************
131
+ *
132
+ * build config for tests
133
+ *
134
+ * NOTE: we can't minify because some tests
135
+ * are checking x.constructor.name, which changes when minified
136
+ *
137
+ *************************************/
138
+ Object.assign(viteConfig.build, {
139
+ sourcemap: true,
140
+ cleanCssOptions: { sourceMap: true },
141
+ minify: false,
142
+ cssMinify: false,
143
+ });
144
+
145
+ viteConfig.build.rolldownOptions ||= {};
146
+ viteConfig.build.rolldownOptions.input ||= {};
147
+ viteConfig.build.rolldownOptions.output ||= {};
148
+
149
+ Object.assign(viteConfig.build.rolldownOptions.input, {
150
+ main: absolutePath("./index.html"),
151
+ });
152
+
153
+ if (existsSync("./tests.html")) {
154
+ Object.assign(viteConfig.build.rolldownOptions.input, {
155
+ tests: absolutePath("./tests.html"),
156
+ });
157
+ }
158
+
159
+ if (existsSync("./tests/index.html")) {
160
+ Object.assign(viteConfig.build.rolldownOptions.input, {
161
+ tests: absolutePath("./tests/index.html"),
162
+ });
163
+ }
164
+
165
+ Object.assign(viteConfig.build.rolldownOptions.output, {
166
+ cleanDir: true,
167
+ strictExecutionOrder: true,
168
+ codeSplitting: {
169
+ groups: [
170
+ // our "test" product-land code happens to not match this pattern
171
+ { name: "tests", test: /[.-]test\.g?(j|t)s/, priority: 10 },
172
+ {
173
+ name: "common",
174
+ minShareCount: 10,
175
+ minSize: 10000,
176
+ maxSize: 1 * 1024 * 1024, // 1~ish MB
177
+ priority: 9,
178
+ },
179
+ {
180
+ name: "uncommon",
181
+ minShareCount: 2,
182
+ minSize: 10000,
183
+ maxSize: 1 * 1024 * 1024, // 1~ish MB
184
+ priority: 5,
185
+ },
186
+ ],
187
+ },
188
+ });
189
+
190
+ return;
191
+ }
192
+ function prod(viteConfig: ResolvedConfig, nvpConfig: Config) {
193
+ Object.assign(viteConfig.build, {
194
+ minify: "oxc",
195
+ sourcemap: true,
196
+ reportCompressedSize: false,
197
+ modulePreload: true,
198
+ cleanCssOptions: { sourceMap: true },
199
+ });
200
+
201
+ viteConfig.build.rolldownOptions ||= {};
202
+ viteConfig.build.rolldownOptions.input ||= {};
203
+ viteConfig.build.rolldownOptions.optimization ||= {};
204
+ viteConfig.build.rolldownOptions.output ||= {};
205
+
206
+ Object.assign(viteConfig.build.rolldownOptions.input, {
207
+ main: absolutePath("./index.html"),
208
+ });
209
+
210
+ Object.assign(viteConfig.build.rolldownOptions.optimization, {
211
+ inlineConst: {
212
+ mode: "smart",
213
+ pass: 3,
214
+ },
215
+ pifeForModuleWrappers: true,
216
+ });
217
+
218
+ Object.assign(viteConfig.build.rolldownOptions.output, {
219
+ minify: true,
220
+ cleanDir: true,
221
+ /**
222
+ * This is needed due to how we manage module state.
223
+ * This can create waterfalls when too much top-level await is used.
224
+ */
225
+ strictExecutionOrder: true,
226
+ /**
227
+ * Code splitting currently makes things worse
228
+ */
229
+ codeSplitting: {
230
+ /**
231
+ * Kind of a shame this isn't automatic based on dynamic import usage
232
+ * in vite8.
233
+ * Kinda forces us to know every potential problem area of the app,
234
+ * rather than rely on automatic optimizations based on import/module usage
235
+ */
236
+ groups: [...(nvpConfig?.production?.codeSplittingGroups ?? [])],
237
+ },
238
+ });
239
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Reasons we have to have babel
3
+ * - decorators
4
+ * - ember-concurrency
5
+ * - scoped-css
6
+ * - template compilation optimization
7
+ */
8
+ import { extensions } from "@embroider/vite";
9
+ import { babel } from "@rollup/plugin-babel";
10
+ import { join, resolve } from "node:path";
11
+ import { parse as oxcParse } from "oxc-parser";
12
+ import { transform } from "oxc-transform";
13
+ import { walk } from "zimmerframe";
14
+
15
+ /**
16
+ * if a file imports any of these, it must be optimize
17
+ */
18
+ const babelTemplateImports = new Set([
19
+ // Templates
20
+ "@ember/template-compiler",
21
+ "@ember/template-compilation",
22
+ "ember-cli-htmlbars",
23
+ "ember-cli-htmlbars-inline-precompile",
24
+ "htmlbars-inline-precompile",
25
+ ]);
26
+
27
+ const babelMacroImports = new Set([
28
+ // Macros
29
+ "@embroider/macros",
30
+ "@glimmer/env",
31
+ "@ember/application/deprecations",
32
+ // Macros only needed in prod
33
+ "@ember/debug",
34
+ ]); // Babel plugins required from libraries
35
+ const babelOtherImports = new Set([
36
+ "ember-concurrency",
37
+ "ember-scoped-css",
38
+ "ember-intl/helpers/format-message",
39
+ ]);
40
+
41
+ const babelRequiredImports = [...babelTemplateImports, ...babelMacroImports, ...babelOtherImports];
42
+
43
+ const counts = {
44
+ total: 0,
45
+ babel: 0,
46
+ why: {
47
+ decorators: 0,
48
+ formatMessage: 0,
49
+ imports: {
50
+ templates: 0,
51
+ macros: 0,
52
+ other: 0,
53
+ },
54
+ initializeRuntimeMacrosConfig: 0,
55
+ },
56
+ };
57
+ export function maybeBabel(options: { parallel?: boolean; configFile: string; env: any }) {
58
+ const { env, parallel, ...restOptions } = options;
59
+ const original = (() => {
60
+ const babelPath = resolve(join(process.cwd(), "./babel.config.mjs"));
61
+
62
+ return babel({
63
+ babelHelpers: "runtime",
64
+ extensions,
65
+ skipPreflightCheck: true,
66
+ ...restOptions,
67
+ configFile: babelPath,
68
+ // Waiting on:
69
+ // https://github.com/rollup/plugins/pull/1956
70
+ // parallel: parallel ?? true,
71
+ });
72
+ })();
73
+
74
+ const babelMacros = new Set(babelRequiredImports);
75
+ if (env.mode === "development") {
76
+ babelMacros.delete("@ember/debug");
77
+ }
78
+
79
+ console.log(original);
80
+
81
+ async function doTransform(code, id) {
82
+ counts.total++;
83
+
84
+ const ext = id.split(".").at(-1);
85
+ const lang = ext === "gjs" ? "js" : ext === "gts" ? "ts" : ext;
86
+
87
+ let needsBabel = false;
88
+
89
+ const estree = await oxcParse(id, code, { lang });
90
+
91
+ walk(
92
+ estree.program,
93
+ /* state */ {},
94
+ {
95
+ Decorator(_node, { stop }) {
96
+ needsBabel = true;
97
+ counts.why.decorators++;
98
+ stop();
99
+ },
100
+ MemberExpression(node, { stop }) {
101
+ if (node.property?.name === "formatMessage" && node.object?.name === "intl") {
102
+ needsBabel = true;
103
+ counts.why.formatMessage++;
104
+ stop();
105
+ }
106
+ },
107
+ ImportDeclaration(node, { stop }) {
108
+ const value = node.source.value;
109
+ if (babelMacros.has(value)) {
110
+ needsBabel = true;
111
+
112
+ if (babelTemplateImports.has(value)) {
113
+ counts.why.imports.templates++;
114
+ } else if (babelMacroImports.has(value)) {
115
+ counts.why.imports.macros++;
116
+ } else {
117
+ counts.why.imports.other++;
118
+ }
119
+
120
+ stop();
121
+ }
122
+ },
123
+ },
124
+ );
125
+
126
+ if (!needsBabel && code.includes("initializeRuntimeMacrosConfig")) {
127
+ counts.why.initializeRuntimeMacrosConfig++;
128
+ needsBabel = true;
129
+ }
130
+
131
+ if (needsBabel) {
132
+ counts.babel++;
133
+
134
+ const result = await original.transform.call(this, code, id);
135
+
136
+ return result;
137
+ }
138
+
139
+ if (ext === "json") {
140
+ return;
141
+ }
142
+
143
+ if (ext === "js" || ext === "gjs") {
144
+ // We don't need to process JS
145
+ return null;
146
+ }
147
+
148
+ const result = await transform(id, code, {
149
+ lang,
150
+ typescript: {
151
+ onlyRemoveTypeImports: true,
152
+ /**
153
+ * We should work towards disabling this.
154
+ */
155
+ allowNamespaces: true,
156
+ removeClassFieldsWithoutInitializer: false,
157
+ rewriteImportExtensions: false,
158
+ },
159
+ });
160
+
161
+ if (result.errors?.length) {
162
+ console.error(`Errors during oxc-transform of ${id}:`);
163
+ for (const err of result.errors) {
164
+ if (err.labels) {
165
+ console.error(err.labels);
166
+ }
167
+ console.error(err.codeframe || err.message);
168
+ }
169
+ throw result.errors;
170
+ }
171
+
172
+ return result;
173
+ }
174
+
175
+ return {
176
+ enforce: "pre",
177
+ buildEnd() {
178
+ if (process.env.INSPECT) {
179
+ console.debug(`Babel usage: ${counts.babel} / ${counts.total}`, counts.why);
180
+ }
181
+ },
182
+ ...original,
183
+ name: "nullvoxpopuli:babel",
184
+ transform: {
185
+ filter: {
186
+ id: {
187
+ include: [/\.js/, /\.gjs/, /\.ts/, /\.gts/],
188
+ exclude: [/\.json/],
189
+ },
190
+ // Enabling this opts us out of template compilation
191
+ // it's an AND instead of OR
192
+ // code: {
193
+ // include: [/initializeRuntimeMacrosConfig/, /precompileTemplate/],
194
+ // },
195
+ },
196
+ handler(code, id) {
197
+ try {
198
+ return doTransform.call(this, code, id);
199
+ } catch (e) {
200
+ // Use VSCode JavaScript Debug Terminal
201
+ // eslint-disable-next-line no-debugger
202
+ debugger;
203
+ throw e;
204
+ }
205
+ },
206
+ },
207
+ };
208
+ }