Skip to content
Draft
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
16 changes: 16 additions & 0 deletions packages/metro-runtime/src/polyfills/require.js
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,22 @@ function loadModuleImplementation(
}
moduleObject.id = moduleId;

if (!moduleObject.importMeta) {
let importMeta;
Object.defineProperty(moduleObject, 'importMeta', {
enumerable: false,
configurable: false,
get: () =>
importMeta ??
(importMeta = {
__proto__: null,
...global[`${__METRO_GLOBAL_PREFIX__}__getImportMetaProperties`]?.(
moduleObject,
),
}),
});
}

// keep args in sync with with defineModuleCode in
// metro/src/Resolver/index.js
// and metro/src/ModuleGraph/worker.js
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ const collectDependencies = require('metro/src/ModuleGraph/worker/collectDepende
const opts = {
importAll: '_$$_IMPORT_ALL',
importDefault: '_$$_IMPORT_DEFAULT',
transformImportMeta: {
objectName: 'module',
propertyName: '_importMeta',
},
};

test('correctly transforms and extracts "import" statements', () => {
Expand Down Expand Up @@ -375,6 +379,26 @@ test('supports `import {default as LocalName}`', () => {
`);
});

test('transforms import.meta', () => {
const code = `
function foo() {
const module = 'bar';
console.log(import.meta.url);
return module;
}
`;

const expected = `
function foo() {
const _module = 'bar';
console.log(module._importMeta.url);
return _module;
}
`;

compare([importExportPlugin], code, expected, opts);
});

function showTransformedDeps(code: string) {
const {dependencies} = collectDependencies(
transformToAst([importExportPlugin], code, opts),
Expand Down
28 changes: 26 additions & 2 deletions packages/metro-transform-plugins/src/import-export-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export type Options = $ReadOnly<{
importDefault: string,
importAll: string,
resolve: boolean,
transformImportMeta: ?{
objectName: string,
propertyName: string,
},
out?: {isESModule: boolean, ...},
}>;

Expand All @@ -46,6 +50,10 @@ type State = {
imports: Array<{node: Statement}>,
importDefault: BabelNode,
importAll: BabelNode,
transformImportMeta: ?{
renameBinding: string,
node: BabelNode,
},
opts: Options,
...
};
Expand Down Expand Up @@ -138,8 +146,6 @@ declare function withLocation<TNode: BabelNode>(
): Array<TNode>;

// eslint-disable-next-line no-redeclare
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function withLocation(node, loc) {
if (Array.isArray(node)) {
return node.map(n => withLocation(n, loc));
Expand All @@ -155,6 +161,15 @@ function importExportPlugin({types: t}: {types: Types, ...}): PluginObj<State> {

return {
visitor: {
MetaProperty(path, state): void {
if (
state.transformImportMeta != null &&
path.node.meta.name === 'import'
) {
path.scope.rename(state.transformImportMeta.renameBinding);
path.replaceWith(t.cloneNode(state.transformImportMeta.node));
}
},
ExportAllDeclaration(
path: NodePath<BabelNodeExportAllDeclaration>,
state: State,
Expand Down Expand Up @@ -497,6 +512,15 @@ function importExportPlugin({types: t}: {types: Types, ...}): PluginObj<State> {
state.imports = [];
state.importAll = t.identifier(state.opts.importAll);
state.importDefault = t.identifier(state.opts.importDefault);
state.transformImportMeta = state.opts.transformImportMeta
? {
renameBinding: state.opts.transformImportMeta.objectName,
node: t.memberExpression(
t.identifier(state.opts.transformImportMeta.objectName),
t.identifier(state.opts.transformImportMeta.propertyName),
),
}
: null;

// Rename declarations at module scope that might otherwise conflict
// with arguments we inject into the module factory.
Expand Down
4 changes: 4 additions & 0 deletions packages/metro-transform-worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,10 @@ async function transformJS(
importAll,
importDefault,
resolve: false,
transformImportMeta: {
objectName: 'module',
propertyName: 'importMeta',
},
} as ImportExportPluginOptions,
]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Object {
"asyncImportMaybeSyncESM": Object {
"default": "export-8: DEFAULT",
"foo": "export-8: FOO",
"url": "metro:///11",
},
"default": "export-4: FOO",
"extraData": Object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ exports[`Metro development server serves bundles via HTTP should serve lazy bund
Object {
"default": "export-8: DEFAULT",
"foo": "export-8: FOO",
"url": "metro://module/11",
}
`;

Expand Down Expand Up @@ -90,6 +91,7 @@ exports[`Metro development server serves bundles via HTTP should serve non-lazy
Object {
"default": "export-8: DEFAULT",
"foo": "export-8: FOO",
"url": "metro://module/11",
}
`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@ test('builds a simple bundle', async () => {
entry: 'import-export/index.js',
});

const object = execBundle(result.code);
const object = execBundle(result.code, {
// Framework/host-defined props
__getImportMetaProperties: module => {
return {
url: new URL(String(module.id), 'metro://'),
};
Comment on lines +31 to +34
Copy link
Contributor

Choose a reason for hiding this comment

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

so this code will be added to react native itself?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

},
});
const cjs = await object.asyncImportCJS;

expect(object).toMatchSnapshot();
Expand Down
14 changes: 14 additions & 0 deletions packages/metro/src/integration_tests/__tests__/server-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ describe('Metro development server serves bundles via HTTP', () => {
test('should serve lazy bundles', async () => {
const object = await downloadAndExec(
'/import-export/index.bundle?platform=ios&dev=true&minify=false&lazy=true',
{
__getImportMetaProperties: module => {
return {
url: new URL(`metro://module/${module.id}`),
};
},
},
);
await expect(object.asyncImportCJS).resolves.toMatchSnapshot();
await expect(object.asyncImportESM).resolves.toMatchSnapshot();
Expand All @@ -111,6 +118,13 @@ describe('Metro development server serves bundles via HTTP', () => {
test('should serve non-lazy bundles by default', async () => {
const object = await downloadAndExec(
'/import-export/index.bundle?platform=ios&dev=true&minify=false',
{
__getImportMetaProperties: module => {
return {
url: new URL(`metro://module/${module.id}`),
};
},
},
);
await expect(object.asyncImportCJS).resolves.toMatchSnapshot();
await expect(object.asyncImportESM).resolves.toMatchSnapshot();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
export default 'export-8: DEFAULT';

export const foo = 'export-8: FOO';
export const url = import.meta.url;
Loading