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

support import sync with dynamic expression #1845

Merged
merged 11 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
50 changes: 49 additions & 1 deletion packages/macros/src/babel/macros-babel-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import error from './error';
import failBuild from './fail-build';
import { Evaluator, buildLiterals } from './evaluate-json';
import type * as Babel from '@babel/core';
import { existsSync, readdirSync } from 'fs';
import { resolve, dirname, join } from 'path';

export default function main(context: typeof Babel): unknown {
let t = context.types;
Expand Down Expand Up @@ -123,7 +125,53 @@ export default function main(context: typeof Babel): unknown {
if (callee.referencesImport('@embroider/macros', 'importSync')) {
let specifier = path.node.arguments[0];
if (specifier?.type !== 'StringLiteral') {
throw new Error(`importSync eager mode doesn't implement non string literal arguments yet`);
let relativePath = '';
let property;
if (specifier.type === 'TemplateLiteral' && specifier.expressions[0].type === 'Identifier') {
patricklx marked this conversation as resolved.
Show resolved Hide resolved
relativePath = specifier.quasis[0].value.cooked!;
property = specifier.expressions[0];
}
// babel might transform template form `../my-path/${id}` to '../my-path/'.concat(id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't notice before that this stuff is distinct from the BinaryExpression support. I don't think it's correct.

Consider:

importSync(`one${two}three${four}`)
// becomes
importSync("one".concat(two, "three").concat(four));

(It would be even better to figure out how to run before preset-env, but I recognize that this is already in an exit hook because it's trying to interoperate with other plugins that adjust the import specifiers themselves.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, i only support "one".concat. this is done by ensuring that the object of the member expression is a string.
one${two}three${four} is also not supported

if (
specifier.type === 'CallExpression' &&
specifier.callee.type === 'MemberExpression' &&
specifier.callee.property.type === 'Identifier' &&
specifier.callee.property.name === 'concat' &&
specifier.callee.object.type === 'StringLiteral' &&
specifier.arguments[0]?.type === 'Identifier'
) {
relativePath = specifier.callee.object.value;
property = specifier.arguments[0];
}
if (property && relativePath && relativePath.startsWith('.')) {
const resolvedPath = resolve(dirname((state as any).filename), relativePath);
let entries: string[] = [];
if (existsSync(resolvedPath)) {
entries = readdirSync(resolvedPath).filter(e => !e.startsWith('.'));
}
const obj = t.objectExpression(
entries.map(e => {
let key = e.split('.')[0];
const rest = e.split('.').slice(1, -1);
if (rest.length) {
key += `.${rest}`;
}
const id = t.callExpression(
state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'),
[state.importUtil.import(path, join(relativePath, key).replace(/\\/g, '/'), '*')]
);
return t.objectProperty(t.stringLiteral(key), id);
})
);
const memberExpr = t.memberExpression(obj, property, true);
path.replaceWith(memberExpr);
state.calledIdentifiers.add(callee.node);
return;
} else {
throw new Error(
`importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier.type}`
);
}
}
path.replaceWith(
t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [
Expand Down
25 changes: 25 additions & 0 deletions packages/macros/tests/babel/import-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,30 @@ describe('importSync', function () {
`);
expect(code).toMatch(/import \* as _importSync\d from "my-plugin"/);
});
test('importSync accepts template argument with dynamic part', () => {
let code = transform(`
import { importSync } from '@embroider/macros';
function getFile(file) {
return importSync(\`../../\${file}\`).default;
}
`);
expect(code).toEqual(`import esc from "../../src/addon/es-compat2";
import * as _importSync0 from "../../README";
import * as _importSync20 from "../../jest.config";
import * as _importSync30 from "../../node_modules";
import * as _importSync40 from "../../package";
import * as _importSync50 from "../../src";
import * as _importSync60 from "../../tests";
function getFile(file) {
return {
"README": esc(_importSync0),
"jest.config": esc(_importSync20),
"node_modules": esc(_importSync30),
"package": esc(_importSync40),
"src": esc(_importSync50),
"tests": esc(_importSync60)
}[file].default;
}`);
});
});
});
Loading