Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile Hbs route templates correctly #1856

Merged
merged 5 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
66 changes: 41 additions & 25 deletions packages/addon-dev/src/rollup-hbs-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { createFilter } from '@rollup/pluginutils';
import type { Plugin, PluginContext, CustomPluginOptions } from 'rollup';
import { readFileSync } from 'fs';
import { hbsToJS } from '@embroider/core';
import { parse as pathParse } from 'path';
import { correspondingTemplate, hbsToJS } from '@embroider/core';
import minimatch from 'minimatch';

export default function rollupHbsPlugin(): Plugin {
export default function rollupHbsPlugin({
excludeColocation,
}: {
excludeColocation?: string[];
}): Plugin {
return {
name: 'rollup-hbs-plugin',
async resolveId(source: string, importer: string | undefined, options) {
Expand All @@ -16,19 +20,26 @@ export default function rollupHbsPlugin(): Plugin {
if (resolution) {
return resolution;
} else {
return maybeSynthesizeComponentJS(this, source, importer, options);
return maybeSynthesizeComponentJS(
this,
source,
importer,
options,
excludeColocation
);
}
},

load(id: string) {
if (hbsFilter(id)) {
let input = readFileSync(id, 'utf8');
let code = hbsToJS(input);
return {
code,
};
return getHbsToJSCode(id);
}
if (getMeta(this, id)) {
let meta = getMeta(this, id);
if (meta) {
if (meta?.type === 'template-js') {
const hbsFile = id.replace(/\.js$/, '.hbs');
return getHbsToJSCode(hbsFile);
}
return {
code: templateOnlyComponent,
};
Expand All @@ -42,7 +53,7 @@ const templateOnlyComponent =
`export default templateOnly();\n`;

type Meta = {
type: 'template-only-component-js';
type: 'template-only-component-js' | 'template-js';
};

function getMeta(context: PluginContext, id: string): Meta | null {
Expand All @@ -54,35 +65,40 @@ function getMeta(context: PluginContext, id: string): Meta | null {
}
}

function correspondingTemplate(filename: string): string {
let { ext } = pathParse(filename);
return filename.slice(0, filename.length - ext.length) + '.hbs';
function getHbsToJSCode(file: string): { code: string } {
let input = readFileSync(file, 'utf8');
let code = hbsToJS(input);
return {
code,
};
}

async function maybeSynthesizeComponentJS(
context: PluginContext,
source: string,
importer: string | undefined,
options: { custom?: CustomPluginOptions; isEntry: boolean }
options: { custom?: CustomPluginOptions; isEntry: boolean },
excludeColocation: string[] | undefined
) {
let templateResolution = await context.resolve(
correspondingTemplate(source),
importer,
{
skipSelf: true,
...options,
}
);
let hbsFilename = correspondingTemplate(source);
let templateResolution = await context.resolve(hbsFilename, importer, {
skipSelf: true,
...options,
});
if (!templateResolution) {
return null;
}
let type = excludeColocation?.some((glob) => minimatch(hbsFilename, glob))
? 'template-js'
: 'template-only-component-js';
// we're trying to resolve a JS module but only the corresponding HBS
// file exists. Synthesize the template-only component JS.
// file exists. Synthesize the JS. The meta states if the hbs corresponds
// to a template-only component or a simple template like a route template.
return {
id: templateResolution.id.replace(/\.hbs$/, '.js'),
meta: {
'rollup-hbs-plugin': {
type: 'template-only-component-js',
type,
},
},
};
Expand Down
4 changes: 2 additions & 2 deletions packages/addon-dev/src/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ export class Addon {
// This wraps standalone .hbs files as Javascript files using inline
// templates. This means special resolving rules for .hbs files aren't
// required for javascript tooling to understand your package.
hbs() {
return hbs();
hbs(options = {}) {
return hbs(options);
}

gjs(options?: { inline_source_map: boolean }) {
Expand Down
2 changes: 2 additions & 0 deletions packages/shared-internals/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"typescript-memoize": "^1.0.1",
"fs-extra": "^9.1.0",
"lodash": "^4.17.21",
"minimatch": "^3.0.4",
"semver": "^7.3.5"
},
"devDependencies": {
Expand All @@ -47,6 +48,7 @@
"@types/fs-extra": "^9.0.12",
"@types/lodash": "^4.14.170",
"@types/js-string-escape": "^1.0.0",
"@types/minimatch": "^3.0.4",
"@types/semver": "^7.3.6",
"@types/tmp": "^0.1.0",
"fixturify": "^2.1.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/shared-internals/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { AppMeta, AddonMeta, PackageInfo } from './metadata';
export { explicitRelative, extensionsPattern, unrelativize, cleanUrl } from './paths';
export { explicitRelative, extensionsPattern, unrelativize, cleanUrl, correspondingTemplate } from './paths';
export { getOrCreate } from './get-or-create';
export { default as Package, V2AddonPackage as AddonPackage, V2AppPackage as AppPackage, V2Package } from './package';
export { default as PackageCache } from './package-cache';
Expand Down
9 changes: 8 additions & 1 deletion packages/shared-internals/src/paths.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { relative, isAbsolute, dirname, join, basename, resolve, sep } from 'path';
import { relative, isAbsolute, dirname, join, basename, resolve, sep, parse as pathParse } from 'path';
import type Package from './package';

// by "explicit", I mean that we want "./local/thing" instead of "local/thing"
Expand Down Expand Up @@ -49,3 +49,10 @@ const postfixRE = /[?#].*$/s;
export function cleanUrl(url: string): string {
return url.replace(postfixRE, '');
}

// given a filename, returns it with the hbs extension
// for instance, passing filename.js returns filename.hbs
export function correspondingTemplate(filename: string): string {
let { ext } = pathParse(filename);
return filename.slice(0, filename.length - ext.length) + '.hbs';
}
16 changes: 15 additions & 1 deletion packages/shared-internals/src/template-colocation-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { dirname } from 'path';
import { explicitRelative, PackageCache } from '.';
import { ImportUtil } from 'babel-import-util';
import makeDebug from 'debug';
import { cleanUrl } from './paths';
import minimatch from 'minimatch';
import { cleanUrl, correspondingTemplate } from './paths';

const debug = makeDebug('embroider:template-colocation-plugin');

Expand Down Expand Up @@ -36,6 +37,14 @@ export interface Options {
// This option is used by Embroider itself to help with v1 addon
// compatibility, other users should probably not use it.
templateExtensions?: string[];

// Default to []
//
// Skip the plugin for files that match the specified globs.
//
// This option is used to prevent the plugin to transform the
// compiled output of hbs files that are not colocated components.
exclude?: string[];
}

interface State {
Expand Down Expand Up @@ -66,6 +75,11 @@ export default function main(babel: typeof Babel) {
}
}

if (state.opts.exclude?.some(glob => minimatch(correspondingTemplate(filename), glob))) {
debug('not handling colocation for %s', filename);
return;
}

debug('handling colocation for %s', filename);
let extensions = state.opts.templateExtensions ?? ['.hbs'];
for (let ext of extensions) {
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 19 additions & 2 deletions tests/scenarios/v2-addon-dev-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ appScenarios
'babel.config.json': `
{
"plugins": [
"@embroider/addon-dev/template-colocation-plugin",
["@embroider/addon-dev/template-colocation-plugin", {
exclude: ['**/just-a-template.hbs'],
}],
"@babel/plugin-transform-class-static-block",
["babel-plugin-ember-template-compilation", {
targetFormat: 'hbs',
Expand Down Expand Up @@ -71,7 +73,9 @@ appScenarios
exclude: ['**/-excluded/**/*'],
}),

addon.hbs(),
addon.hbs({
excludeColocation: ['**/just-a-template.hbs'],
}),
addon.gjs(),
addon.dependencies(),

Expand Down Expand Up @@ -113,6 +117,7 @@ appScenarios
flip
</button>
`,
'just-a-template.hbs': `<p>I am not a component but a template.</p>`,
'out.hbs': `
<out>{{yield}}</out>
`,
Expand Down Expand Up @@ -244,13 +249,15 @@ appScenarios
'./components/demo/button.js': './dist/_app_/components/demo/button.js',
'./components/single-file-component.js': './dist/_app_/components/single-file-component.js',
'./components/demo/index.js': './dist/_app_/components/demo/index.js',
'./components/demo/just-a-template.js': './dist/_app_/components/demo/just-a-template.js',
'./components/demo/out.js': './dist/_app_/components/demo/out.js',
'./components/demo/namespace/namespace-me.js': './dist/_app_/components/demo/namespace/namespace-me.js',
});
});

test('the addon has expected public entrypoints', async function () {
expectFile('dist/components/demo/index.js').exists();
expectFile('dist/components/demo/just-a-template.js').exists();
expectFile('dist/components/demo/out.js').exists();
expectFile('dist/components/demo/namespace-me.js').exists();
expectFile('dist/components/-excluded/never-import-this.js').doesNotExist();
Expand All @@ -260,6 +267,9 @@ appScenarios
expectFile('dist/_app_/components/demo/index.js').matches(
'export { default } from "v2-addon/components/demo/index"'
);
expectFile('dist/_app_/components/demo/just-a-template.js').matches(
'export { default } from "v2-addon/components/demo/just-a-template"'
);
expectFile('dist/_app_/components/demo/out.js').matches(
'export { default } from "v2-addon/components/demo/out"'
);
Expand All @@ -274,6 +284,13 @@ appScenarios
/TEMPLATE = precompileTemplate\("Hello there/,
'template is still in hbs format'
);

expectFile(
'dist/components/demo/just-a-template.js'
).equalsCode(`import { precompileTemplate } from '@ember/template-compilation';
var justATemplate = precompileTemplate("<p>I am not a component but a template.</p>");
export { justATemplate as default };
//# sourceMappingURL=just-a-template.js.map`);
});

test('gjs components compiled correctly', async function () {
Expand Down
Loading