From 86d33976b2a2f0a2730f4a2bc9a6558dc54dd56d Mon Sep 17 00:00:00 2001 From: NGBAMA William Date: Thu, 23 Jan 2025 03:59:30 +0100 Subject: [PATCH 1/2] feat(compiler): auto import unison if needed --- packages/compiler/src/index.js | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/packages/compiler/src/index.js b/packages/compiler/src/index.js index 716a0b4..f2a3702 100644 --- a/packages/compiler/src/index.js +++ b/packages/compiler/src/index.js @@ -291,6 +291,22 @@ export default function (babel, opts = {}) { return false; } + const hasUnisonVisitor = { + ImportDeclaration(path) { + const declaration = path.node; + if (declaration.source.value === moduleName) { + for (const specifier of declaration.specifiers) { + if (specifier.local.name === UNISON_NAME) { + currentUnisonName = specifier.imported.name + this.hasUnison(); + path.stop(); + break; + } + } + } + }, +}; + let mode = opts.mode || 'manual'; return { @@ -299,13 +315,28 @@ export default function (babel, opts = {}) { Program: { enter(path) { program = path; + + let unisonImported = false + path.traverse(hasUnisonVisitor, { hasUnison: () => unisonImported = true }); + if (!unisonImported) { + const id = t.identifier(UNISON_NAME) + // add: import { $unison } from 'module_name'; + program.unshiftContainer('body', [ + t.importDeclaration( + [t.importSpecifier(id, id)], + t.stringLiteral(moduleName), + ), + ]); + } + if (noUnison(path.node.directives)) path.stop(); if (mode === 'directive' && useUnison(path.node.directives)) { mode = 'full'; path.get('directives.0').replaceWith(t.directive(t.directiveLiteral('use client'))) } + if (rsxIdentifier) return; rsxIdentifier = program.scope.generateUidIdentifier('rsx'); program.unshiftContainer('body', [ @@ -313,9 +344,6 @@ export default function (babel, opts = {}) { ]); }, }, - ImportSpecifier(path) { - if (path.node.imported.name === UNISON_NAME) currentUnisonName = path.node.local.name; - }, FunctionDeclaration(path) { // Looking for : // function Component() {}; $unison(Component); From 289d64619de94ab34b464686aa51845873e9d0d8 Mon Sep 17 00:00:00 2001 From: NGBAMA William Date: Thu, 23 Jan 2025 04:00:57 +0100 Subject: [PATCH 2/2] chore: add changeset --- .changeset/perfect-ties-whisper.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/perfect-ties-whisper.md diff --git a/.changeset/perfect-ties-whisper.md b/.changeset/perfect-ties-whisper.md new file mode 100644 index 0000000..97ad664 --- /dev/null +++ b/.changeset/perfect-ties-whisper.md @@ -0,0 +1,5 @@ +--- +'babel-plugin-unisonjs-compiler': minor +--- + +Auto import unison if necessary