Skip to content

Commit 9d5b6b8

Browse files
committed
Make option getModuleId be used with relative imports
1 parent 6609699 commit 9d5b6b8

5 files changed

Lines changed: 150 additions & 9 deletions

File tree

‎packages/babel-helper-module-transforms/src/index.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import assert from "node:assert";
2+
import path from "node:path";
23
import { template, types as t } from "@babel/core";
34

45
import { isModule } from "@babel/helper-module-imports";
@@ -21,10 +22,11 @@ import type { NodePath } from "@babel/core";
2122

2223
export { buildDynamicImport } from "./dynamic-import.ts";
2324

24-
export { default as getModuleName } from "./get-module-name.ts";
25+
import getModuleName from "./get-module-name.ts";
26+
import type { PluginOptions } from "./get-module-name.ts";
2527
export type { PluginOptions } from "./get-module-name.ts";
2628

27-
export { hasExports, isSideEffectImport, isModule, rewriteThis };
29+
export { hasExports, isSideEffectImport, isModule, rewriteThis, getModuleName };
2830

2931
export interface RewriteModuleStatementsAndPrepareHeaderOptions {
3032
exportName?: string;
@@ -249,6 +251,68 @@ export function buildNamespaceInitStatements(
249251
return statements;
250252
}
251253

254+
export function withExtension(filename: string, ext?: string | null): string {
255+
return null == ext ? filename : filename.replace(/\.\w*$/, ext);
256+
}
257+
258+
const reWinPathSep = /\\/g;
259+
260+
export function normalizePathSeparators(srcPath: string): string {
261+
return path.sep === "\\" ? srcPath.replace(reWinPathSep, "/") : srcPath;
262+
}
263+
264+
const reRelativePath = /^\.*[\\/]/;
265+
266+
interface ImportPaths {
267+
filename: string | undefined;
268+
filenameRelative: string | undefined;
269+
}
270+
271+
export function resolveRelativeImportPaths(
272+
importRelative: string,
273+
rootOpts: { filename?: string; filenameRelative?: string },
274+
): ImportPaths {
275+
if (!reRelativePath.test(importRelative)) {
276+
return {
277+
filename: importRelative,
278+
filenameRelative: importRelative,
279+
};
280+
}
281+
const rootAbsolute = rootOpts.filename;
282+
const rootRelativeSource = rootOpts.filenameRelative;
283+
const importAbsolute =
284+
rootAbsolute &&
285+
normalizePathSeparators(
286+
path.join(path.dirname(rootAbsolute), importRelative),
287+
);
288+
const importRelativeSource =
289+
rootRelativeSource &&
290+
normalizePathSeparators(
291+
path.join(path.dirname(rootRelativeSource), importRelative),
292+
);
293+
return {
294+
filename: importAbsolute || undefined,
295+
filenameRelative: importRelativeSource || undefined,
296+
};
297+
}
298+
299+
export function amdImportId(
300+
importRelative: string,
301+
rootOpts: { filename?: string; filenameRelative?: string },
302+
pluginOpts: PluginOptions & { importFileExt?: string },
303+
): string {
304+
if (!reRelativePath.test(importRelative)) return importRelative;
305+
return (
306+
getModuleName(
307+
{
308+
...rootOpts,
309+
...resolveRelativeImportPaths(importRelative, rootOpts),
310+
},
311+
pluginOpts,
312+
) || withExtension(importRelative, pluginOpts.importFileExt)
313+
);
314+
}
315+
252316
interface ReexportParts {
253317
exports: string;
254318
exportName: string;

‎packages/babel-plugin-transform-modules-umd/src/index.ts‎

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import {
1010
ensureStatementsHoisted,
1111
wrapInterop,
1212
getModuleName,
13+
withExtension,
14+
resolveRelativeImportPaths,
15+
amdImportId,
1316
} from "@babel/helper-module-transforms";
1417
import type { PluginOptions } from "@babel/helper-module-transforms";
1518
import { types as t, template, type NodePath } from "@babel/core";
@@ -45,6 +48,8 @@ export interface Options extends PluginOptions {
4548
exactGlobals?: boolean;
4649
globals?: Record<string, string>;
4750
importInterop?: RewriteModuleStatementsAndPrepareHeaderOptions["importInterop"];
51+
/** Extension applied to relative CommonJS `require()` paths, e.g. ".js". */
52+
importFileExt?: string;
4853
/** @deprecated Use the `constantReexports` and `enumerableModuleMeta` assumptions instead. */
4954
loose?: boolean;
5055
noInterop?: boolean;
@@ -70,6 +75,7 @@ export default declare((api, options: Options) => {
7075
strictMode,
7176
noInterop,
7277
importInterop,
78+
importFileExt,
7379
} = options;
7480

7581
const constantReexports =
@@ -96,7 +102,8 @@ export default declare((api, options: Options) => {
96102
let initAssignments = [];
97103

98104
if (exactGlobals) {
99-
const globalName = browserGlobals[moduleNameOrBasename];
105+
const globalName =
106+
browserGlobals[filename] || browserGlobals[moduleNameOrBasename];
100107

101108
if (globalName) {
102109
initAssignments = [];
@@ -136,10 +143,12 @@ export default declare((api, options: Options) => {
136143
browserGlobals: Record<string, string>,
137144
exactGlobals: boolean | undefined,
138145
source: string,
146+
filename: string | undefined,
139147
) {
140148
let memberExpression: t.MemberExpression;
141149
if (exactGlobals) {
142-
const globalRef = browserGlobals[source];
150+
const globalRef =
151+
(filename && browserGlobals[filename]) || browserGlobals[source];
143152
if (globalRef) {
144153
memberExpression = globalRef
145154
.split(".")
@@ -173,9 +182,10 @@ export default declare((api, options: Options) => {
173182
exit(path) {
174183
if (!isModule(path)) return;
175184

185+
const fileOpts = this.file.opts;
176186
const browserGlobals = globals || {};
177187

178-
const moduleName = getModuleName(this.file.opts, options);
188+
const moduleName = getModuleName(fileOpts, options);
179189
let moduleNameLiteral: t.StringLiteral | undefined;
180190
if (moduleName) moduleNameLiteral = t.stringLiteral(moduleName);
181191

@@ -208,14 +218,25 @@ export default declare((api, options: Options) => {
208218
}
209219

210220
for (const [source, metadata] of meta.source) {
211-
amdArgs.push(t.stringLiteral(source));
221+
const {
222+
filename: sourceFilename,
223+
filenameRelative: sourceRelative,
224+
} = resolveRelativeImportPaths(source, fileOpts);
225+
amdArgs.push(
226+
t.stringLiteral(amdImportId(source, fileOpts, options)),
227+
);
212228
commonjsArgs.push(
213229
t.callExpression(t.identifier("require"), [
214-
t.stringLiteral(source),
230+
t.stringLiteral(withExtension(source, importFileExt)),
215231
]),
216232
);
217233
browserArgs.push(
218-
buildBrowserArg(browserGlobals, exactGlobals, source),
234+
buildBrowserArg(
235+
browserGlobals,
236+
exactGlobals,
237+
source,
238+
sourceRelative || sourceFilename,
239+
),
219240
);
220241
importNames.push(t.identifier(metadata.name));
221242

@@ -267,7 +288,10 @@ export default declare((api, options: Options) => {
267288
GLOBAL_TO_ASSIGN: buildBrowserInit(
268289
browserGlobals,
269290
exactGlobals,
270-
this.filename || "unknown",
291+
fileOpts.filenameRelative ||
292+
fileOpts.filename ||
293+
this.filename ||
294+
"unknown",
271295
moduleNameLiteral,
272296
),
273297
}) as t.Statement,
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import fooBar1 from "foo-bar";
2+
import fooBar2 from "./mylib/foo-bar";
3+
import fileExt from "./file.mjs";
4+
import fizzBuzz from "fizzbuzz";
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
var reSourceRoot = /^umd\/imports-get-module-id\//;
3+
4+
module.exports = {
5+
"plugins": [
6+
"external-helpers",
7+
[
8+
"transform-modules-umd",
9+
{
10+
"globals": {
11+
"foo-bar": "fooBAR",
12+
"fizzbuzz": "fizz.buzz",
13+
"umd/imports-get-module-id/input.mjs": "customModuleId.input",
14+
"umd/imports-get-module-id/mylib/foo-bar": "customModuleId.mylib.fooBar",
15+
"umd/imports-get-module-id/file.mjs": "customModuleId.file",
16+
},
17+
"exactGlobals": true,
18+
"importFileExt": ".js"
19+
}
20+
]
21+
],
22+
moduleIds: true,
23+
getModuleId(name) {
24+
if (reSourceRoot.test(name)) {
25+
return 'custom-module-id/'+name.replace(reSourceRoot, '');
26+
}
27+
}
28+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
(function (global, factory) {
2+
if (typeof define === "function" && define.amd) {
3+
define("custom-module-id/input", ["foo-bar", "custom-module-id/mylib/foo-bar", "custom-module-id/file", "fizzbuzz"], factory);
4+
} else if (typeof exports !== "undefined") {
5+
factory(require("foo-bar"), require("./mylib/foo-bar"), require("./file.js"), require("fizzbuzz"));
6+
} else {
7+
var mod = {
8+
exports: {}
9+
};
10+
factory(global.fooBAR, global.customModuleId.mylib.fooBar, global.customModuleId.file, global.fizz.buzz);
11+
global.customModuleId = global.customModuleId || {};
12+
global.customModuleId.input = mod.exports;
13+
}
14+
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_fooBar, _fooBar2, _file, _fizzbuzz) {
15+
"use strict";
16+
17+
_fooBar = babelHelpers.interopRequireDefault(_fooBar);
18+
_fooBar2 = babelHelpers.interopRequireDefault(_fooBar2);
19+
_file = babelHelpers.interopRequireDefault(_file);
20+
_fizzbuzz = babelHelpers.interopRequireDefault(_fizzbuzz);
21+
});

0 commit comments

Comments
 (0)