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

add a basic implementation of the gjs rollup plugin #1518

Merged
merged 3 commits into from
Jul 20, 2023
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
1 change: 1 addition & 0 deletions packages/addon-dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@embroider/core": "workspace:^",
"@rollup/pluginutils": "^4.1.1",
"assert-never": "^1.2.1",
"content-tag": "^1.0.0",
"fs-extra": "^10.0.0",
"minimatch": "^3.0.4",
"rollup-plugin-copy-assets": "^2.0.3",
Expand Down
83 changes: 83 additions & 0 deletions packages/addon-dev/src/rollup-gjs-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { createFilter } from '@rollup/pluginutils';
import type { Plugin, PluginContext, ResolvedId } from 'rollup';
import { readFileSync } from 'fs';
import { Preprocessor } from 'content-tag';

const PLUGIN_NAME = 'rollup-gjs-plugin';

const processor = new Preprocessor();
// import { parse as pathParse } from 'path';

export default function rollupGjsPlugin(): Plugin {
return {
name: PLUGIN_NAME,
async resolveId(source: string, importer: string | undefined, options) {
let resolution = await this.resolve(source, importer, {
skipSelf: true,
...options,
});

if (resolution) {
return maybeRewriteGJS(resolution);
}
},

load(id: string) {
const meta = getMeta(this, id);
if (!meta) {
return;
}

this.addWatchFile(meta.originalId);
let input = readFileSync(meta.originalId, 'utf8');
let code = processor.process(input);
return {
code,
};
},
};
}

type Meta = {
originalId: string;
};

function getMeta(context: PluginContext, id: string): Meta | null {
const meta = context.getModuleInfo(id)?.meta?.[PLUGIN_NAME];
if (meta) {
return meta as Meta;
} else {
return null;
}
}

const gjsFilter = createFilter('**/*.g{j,t}s');

function maybeRewriteGJS(resolution: ResolvedId) {
if (!gjsFilter(resolution.id)) {
return null;
}

let id;

if (resolution.id.endsWith('.gjs')) {
id = resolution.id.replace(/\.gjs$/, '.js');
} else if (resolution.id.endsWith('.gts')) {
id = resolution.id.replace(/\.gts$/, '.ts');
} else {
throw new Error(
'Unexpected issues in the plugin-rollup-gjs - an unexpected file made its way throught the pluginUtils filter'
);
}

// This creates an `*.js` or `*.ts` that **replaces** the .gjs or .gts file that we will populate in `load()` hook.
return {
...resolution,
id,
meta: {
[PLUGIN_NAME]: {
originalId: resolution.id,
},
},
};
}
5 changes: 5 additions & 0 deletions packages/addon-dev/src/rollup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { default as hbs } from './rollup-hbs-plugin';
import { default as gjs } from './rollup-gjs-plugin';
import { default as publicEntrypoints } from './rollup-public-entrypoints';
import { default as appReexports } from './rollup-app-reexports';
import { default as clean } from 'rollup-plugin-delete';
Expand Down Expand Up @@ -45,6 +46,10 @@ export class Addon {
return hbs();
}

gjs() {
return gjs();
}

// By default rollup does not clear the output directory between builds. This
// does that.
clean() {
Expand Down
16 changes: 11 additions & 5 deletions pnpm-lock.yaml

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

1 change: 1 addition & 0 deletions tests/scenarios/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@babel/plugin-proposal-decorators": "^7.17.2",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-class-properties": "^7.16.7",
"@babel/plugin-transform-class-static-block": "^7.22.5",
"@babel/plugin-transform-runtime": "^7.18.6",
"@babel/plugin-transform-typescript": "^7.22.5",
"@babel/preset-env": "^7.16.11",
Expand Down
35 changes: 30 additions & 5 deletions tests/scenarios/v2-addon-dev-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ appScenarios
],
"plugins": [
"@embroider/addon-dev/template-colocation-plugin",
"@babel/plugin-transform-class-static-block",
["babel-plugin-ember-template-compilation", {
targetFormat: 'hbs',
compilerPath: 'ember-source/dist/ember-template-compiler',
Expand Down Expand Up @@ -67,15 +68,12 @@ appScenarios
'components/**/*.js',
]),

addon.appReexports([
'components/demo/index.js',
'components/demo/out.js',
'components/demo/namespace-me.js',
], {
addon.appReexports(['components/**/*.js'], {
mapFilename: (name) => reexportMappings[name] || name,
}),

addon.hbs(),
addon.gjs(),
addon.dependencies(),

babel({ babelHelpers: 'bundled' }),
Expand All @@ -102,6 +100,10 @@ appScenarios
},
src: {
components: {
'single-file-component.gjs': `import Component from '@glimmer/component';
export default class SingleFileComponent extends Component {
<template><div data-test-single-file-component>Hello {{@message}}</div></template>
}`,
demo: {
'button.hbs': `
<button {{on 'click' @onClick}}>
Expand Down Expand Up @@ -147,6 +149,7 @@ appScenarios
addon.linkDependency('@embroider/addon-dev', { baseDir: __dirname });
addon.linkDependency('babel-plugin-ember-template-compilation', { baseDir: __dirname });
addon.linkDevDependency('@babel/core', { baseDir: __dirname });
addon.linkDevDependency('@babel/plugin-transform-class-static-block', { baseDir: __dirname });
addon.linkDevDependency('@babel/plugin-transform-class-properties', { baseDir: __dirname });
addon.linkDevDependency('@babel/plugin-proposal-decorators', { baseDir: __dirname });
addon.linkDevDependency('@babel/preset-env', { baseDir: __dirname });
Expand Down Expand Up @@ -176,6 +179,12 @@ appScenarios
assert.dom('out').containsText('true');
});

test('<SingleFileComponent @message="bob" />', async function(assert) {
await render(hbs\`<SingleFileComponent @message="bob" />\`);

assert.dom().containsText('Hello bob');
})

test('transform worked', async function (assert) {
await render(hbs\`<Demo />\`);
assert.dom('[data-test="should-transform"]').containsText('iWasTransformed');
Expand Down Expand Up @@ -222,6 +231,8 @@ appScenarios

test('package.json is modified appropriately', async function () {
expectFile('package.json').json('ember-addon.app-js').deepEquals({
'./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/out.js': './dist/_app_/components/demo/out.js',
'./components/demo/namespace/namespace-me.js': './dist/_app_/components/demo/namespace/namespace-me.js',
Expand All @@ -248,6 +259,20 @@ appScenarios
'template is still in hbs format'
);
});

test('gjs components compiled correctly', async function () {
expectFile('dist/components/single-file-component.js').equalsCode(`import Component from '@glimmer/component';
import { precompileTemplate } from '@ember/template-compilation';
import { setComponentTemplate } from '@ember/component';

class SingleFileComponent extends Component {}
setComponentTemplate(precompileTemplate(\"<div data-test-single-file-component>Hello {{@message}}</div>\", {
strictMode: true
}), SingleFileComponent);

export { SingleFileComponent as default };
//# sourceMappingURL=single-file-component.js.map`);
});
});

Qmodule('Consuming app', function () {
Expand Down