Skip to content

Commit

Permalink
upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
patricklx committed May 2, 2024
1 parent 4f04e31 commit 7f58578
Show file tree
Hide file tree
Showing 13 changed files with 145 additions and 174 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,6 @@
!rollup.config.mjs
!tsconfig.json
!tsconfig.lib.json
!webpack.js
!webpack.js
!babel.config.lib.json
!babel.config.ember.json
2 changes: 1 addition & 1 deletion addon-main.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ Object.assign(module.exports, {
},

_buildPlugin() {
return require('./dist/lib/babel-plugin').hotAstProcessor;
return require('./dist/lib/babel-plugin').hotAstProcessor.transform;
},
});
11 changes: 11 additions & 0 deletions babel.config.ember.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"plugins": [
["@babel/plugin-transform-typescript", { "allExtensions": true, "onlyRemoveTypeImports": true, "allowDeclareFields": true }],
"@embroider/addon-dev/template-colocation-plugin",
["babel-plugin-ember-template-compilation", {
"targetFormat": "hbs",
"transforms": []
}],
["@babel/plugin-proposal-decorators", { "version": "legacy" }]
]
}
File renamed without changes.
56 changes: 37 additions & 19 deletions lib/babel-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
NodeVisitor,
WalkerPath
} from '@glimmer/syntax';
import { ImportUtil } from 'babel-import-util';

export type BabelTypes = typeof BabelTypesNamespace;

Expand Down Expand Up @@ -96,33 +97,29 @@ class HotAstProcessor {
}

transform(env: ASTPluginEnvironment) {
if (process.env['EMBER_VITE_HMR_ENABLED'] !== 'true') {
return {
visitor: {}
}
}
const meta = this.meta;
const imports = [...env.locals];
const importVar = env.meta.jsutils.bindExpression('null', null, { nameHint: 'template__imports__' });
const importVar = meta.importVar || env.meta.jsutils.bindExpression('null', null, { nameHint: 'template__imports__' });
meta.importVar = importVar;
const findImport = function findImport(specifier) {
return meta.babelProgram.body.find(b => b.type === 'ImportDeclaration' && b.specifiers.some(s => s.local.name === specifier));
}
return {
visitor: {
...this.buildVisitor({
importVar,
imports,
importBindings: meta.importBindings,
babelProgram: meta.babelProgram
}),
Template: {
exit() {
for (const local of env.locals) {
if (findImport(local)) {
meta.importBindings.add(local);
}
}
}
}
},
};
}

buildVisitor({ importVar, imports, babelProgram }: { importVar: string, imports: string[], babelProgram: Program }) {
buildVisitor({ importVar, importBindings, babelProgram }: { importVar: string, importBindings: Set<string>, babelProgram: Program }) {

const findImport = function findImport(specifier) {
return babelProgram.body.find(b => b.type === 'ImportDeclaration' && b.specifiers.some(s => s.local.name === specifier));
Expand Down Expand Up @@ -186,9 +183,10 @@ class HotAstProcessor {
return;
}
if (importVar) {
if (imports.includes(node.original) && findImport(node.original)) {
if (findImport(node.original)) {
node.original = `${importVar}.${original}` + node.original.split('.').slice(1).join('.');
node.parts = node.original.split('.');
importBindings.add(original)
}
return;
}
Expand All @@ -197,10 +195,12 @@ class HotAstProcessor {
element: ASTv1.ElementNode,
p: WalkerPath<ASTv1.ElementNode>,
) => {
if (findBlockParams(element.tag.split('.')[0], p)) return;
const original = element.tag.split('.')[0];
if (findBlockParams(original, p)) return;
if (importVar) {
if (imports.includes(element.tag) && findImport(element.tag)) {
element.tag = `${importVar}.${element.tag}`;
if (findImport(original)) {
element.tag = `${importVar}.${original}`;
importBindings.add(original)
}
return;
}
Expand All @@ -227,8 +227,26 @@ export default function hotReplaceAst(
},
visitor: {
Program(path, state) {
t.class
path.node.body;
if (!hotAstProcessor.meta.importVar) {
return;
}
if (process.env['EMBER_VITE_HMR_ENABLED'] !== 'true') {
return;
}
const util = new ImportUtil(t, path);
const tracked = util.import(path, '@glimmer/tracking', 'tracked')
const klass = t.classExpression(path.scope.generateUidIdentifier('Imports'), null, t.classBody([]));
const bindings = [...hotAstProcessor.meta.importBindings].sort();
for (const local of bindings) {
klass.body.body.push(t.classProperty(t.identifier(local), t.identifier(local), null, [t.decorator(tracked)]));
}

const assign = t.assignmentExpression('=', t.identifier(hotAstProcessor.meta.importVar), klass);

const varDeclaration = path.node.body.findIndex((e: BabelTypesNamespace.Statement) => e.type === 'VariableDeclaration' && (e.declarations[0]!.id as BabelTypesNamespace.Identifier).name === hotAstProcessor.meta.importVar) + 1;
const lastImportIndex = path.node.body.findLastIndex((e: BabelTypesNamespace.Statement) => e.type === 'ImportDeclaration') + 1

path.node.body.splice(Math.max(varDeclaration, lastImportIndex), 0, assign);
}
},
} as PluginObj;
Expand Down
6 changes: 5 additions & 1 deletion lib/hmr.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import path from 'path';
import { Plugin } from 'vite';

export function hmr() {
export function hmr(enableViteHmrForModes: string[] = ['development']): Plugin {
return {
name: 'hmr-plugin',
enforce: 'post',
configResolved(config) {
process.env['EMBER_VITE_HMR_ENABLED'] = enableViteHmrForModes.includes(config.mode).toString()
},
resolveId(id) {
if (id.startsWith('/@id/embroider_virtual:')) {
return this.resolve(id.replace('/@id/', ''), path.join(process.cwd(), 'package.json'));
Expand Down
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ember-vite-hmr",
"version": "0.6.9",
"version": "1.0.0",
"keywords": [
"ember-addon"
],
Expand Down Expand Up @@ -85,6 +85,7 @@
"@types/node": "^15.12.2",
"@types/semver": "^7.3.6",
"babel-plugin-ember-template-compilation": "^2.2.2",
"babel-import-util": "2.0.3",
"concurrently": "^8.0.1",
"ember-resolver": "^11.0.1",
"ember-source": "^5.3.0",
Expand All @@ -101,7 +102,8 @@
},
"peerDependencies": {
"@embroider/compat": "*",
"babel-plugin-ember-template-compilation": "^2.2.2"
"babel-plugin-ember-template-compilation": "^2.2.2",
"babel-import-util": "2.0.3"
},
"engines": {
"node": "12.* || 14.* || >= 16"
Expand All @@ -114,8 +116,8 @@
"type": "addon",
"main": "addon-main.cjs",
"app-js": {
"./initializers/webpack-hot-reload.js": "./dist/_app_/initializers/webpack-hot-reload.js",
"./services/webpack-hot-reload.js": "./dist/_app_/services/webpack-hot-reload.js"
"./initializers/vite-hot-reload.js": "./dist/_app_/initializers/vite-hot-reload.js",
"./services/vite-hot-reload.js": "./dist/_app_/services/vite-hot-reload.js"
}
},
"exports": {
Expand Down
1 change: 1 addition & 0 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export default {
babel({
extensions: ['.js', '.gjs', '.ts', '.gts'],
babelHelpers: 'bundled',
configFile: 'babel.config.ember.json'
}),

// Ensure that standalone .hbs files are properly integrated as Javascript.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export function initialize(application) {
application.__container__.lookup('service:webpack-hot-reload');
application.__container__.lookup('service:vite-hot-reload');
const resolver =
application.__registry__.resolver._fallback ||
application.__registry__.resolver;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ if (import.meta.hot) {
};
}

export default class WebpackHotReloadService extends Service {
export default class ViteHotReloadService extends Service {
declare container: any;
@service() router!: RouterService;

Expand Down Expand Up @@ -206,6 +206,6 @@ export default class WebpackHotReloadService extends Service {
// like `@service('hot-reload') declare altName: HotReloadService;`.
declare module '@ember/service' {
interface Registry {
'hot-reload': WebpackHotReloadService;
'hot-reload': ViteHotReloadService;
}
}
Loading

0 comments on commit 7f58578

Please sign in to comment.