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

Add rewriteImportExtensions option to TS preset #15913

Merged
merged 3 commits into from
Sep 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/babel-preset-typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import syntaxJSX from "@babel/plugin-syntax-jsx";
import transformModulesCommonJS from "@babel/plugin-transform-modules-commonjs";
import normalizeOptions from "./normalize-options.ts";
import type { Options } from "./normalize-options.ts";
import pluginRewriteTSImports from "./plugin-rewrite-ts-imports.ts";

export default declarePreset((api, opts: Options) => {
api.assertVersion(7);
Expand All @@ -18,6 +19,7 @@ export default declarePreset((api, opts: Options) => {
jsxPragmaFrag,
onlyRemoveTypeImports,
optimizeConstEnums,
rewriteImportExtensions,
} = normalizeOptions(opts);

const pluginOptions = process.env.BABEL_8_BREAKING
Expand Down Expand Up @@ -59,6 +61,7 @@ export default declarePreset((api, opts: Options) => {
const disableExtensionDetect = allExtensions || ignoreExtensions;

return {
plugins: rewriteImportExtensions ? [pluginRewriteTSImports] : [],
overrides: disableExtensionDetect
? [{ plugins: getPlugins(isTSX, disallowAmbiguousJSXLike) }]
: // Only set 'test' if explicitly requested, since it requires that
Expand Down
13 changes: 12 additions & 1 deletion packages/babel-preset-typescript/src/normalize-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface Options {
jsxPragmaFrag?: string;
onlyRemoveTypeImports?: boolean;
optimizeConstEnums?: boolean;
rewriteImportExtensions?: boolean;

// TODO: Remove in Babel 8
allExtensions?: boolean;
Expand All @@ -19,14 +20,17 @@ export interface Options {
export default function normalizeOptions(options: Options = {}) {
let { allowNamespaces = true, jsxPragma, onlyRemoveTypeImports } = options;

const TopLevelOptions = {
const TopLevelOptions: {
[Key in keyof Omit<Options, "allowDeclareFields">]-?: Key;
} = {
ignoreExtensions: "ignoreExtensions",
allowNamespaces: "allowNamespaces",
disallowAmbiguousJSXLike: "disallowAmbiguousJSXLike",
jsxPragma: "jsxPragma",
jsxPragmaFrag: "jsxPragmaFrag",
onlyRemoveTypeImports: "onlyRemoveTypeImports",
optimizeConstEnums: "optimizeConstEnums",
rewriteImportExtensions: "rewriteImportExtensions",

// TODO: Remove in Babel 8
allExtensions: "allExtensions",
Expand Down Expand Up @@ -121,6 +125,12 @@ export default function normalizeOptions(options: Options = {}) {
false,
);

const rewriteImportExtensions = v.validateBooleanOption(
TopLevelOptions.rewriteImportExtensions,
options.rewriteImportExtensions,
false,
);

const normalized: Options = {
ignoreExtensions,
allowNamespaces,
Expand All @@ -129,6 +139,7 @@ export default function normalizeOptions(options: Options = {}) {
jsxPragmaFrag,
onlyRemoveTypeImports,
optimizeConstEnums,
rewriteImportExtensions,
};
if (!process.env.BABEL_8_BREAKING) {
normalized.allExtensions = allExtensions;
Expand Down
24 changes: 24 additions & 0 deletions packages/babel-preset-typescript/src/plugin-rewrite-ts-imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { declare } from "@babel/helper-plugin-utils";
import type { types as t } from "@babel/core";
import type { NodePath } from "@babel/traverse";

export default declare(function ({ types: t }) {
return {
JLHwung marked this conversation as resolved.
Show resolved Hide resolved
name: "preset-typescript/plugin-rewrite-ts-imports",
visitor: {
"ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration"({
node,
}: NodePath<
t.ImportDeclaration | t.ExportAllDeclaration | t.ExportNamedDeclaration
>) {
const { source } = node;
const kind = t.isImportDeclaration(node)
? node.importKind
: node.exportKind;
if (kind === "value" && source && /[\\/]/.test(source.value)) {
source.value = source.value.replace(/(\.[mc]?)ts$/, "$1js");
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
source.value = source.value.replace(/(\.[mc]?)ts$/, "$1js");
source.value = source.value.replace(/(\/.+?\.[mc]?)ts$/, "$1js");

To cover the edge case mentioned by @bakkot, unless the import is specified as import "/tmp/soundcloud.ts", which we can't tackle without resolving it first.

Copy link
Member

Choose a reason for hiding this comment

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

if (!source.includes("@"))

We may also want to exclude @, such as @org/mod.ts.

Copy link
Member Author

Choose a reason for hiding this comment

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

I would only special-case import specifiers that contain no \ or /, because the only way a specifier without / could work is if it maps to a folder (using Node.js' resolution algorithm) or to a file without any rewriting (using an import map).

For example, I have a project with an import map that includes the following:

{
  "imports": {
    "@/": "./",
    "@components/": "./frontend/components/"

As such, @/foo.ts and @components/foo.ts both map to files and not to directories (and thus they would need their .ts extension to be rewritten).

I would prefer to either (in other of preference):

  1. do nothing, and if somebody has some imports that must not be rewritten they can disable the option for that file
  2. only ignore imports with no /
  3. extract the plugin to its own package, and when it's used directly allow passing a function originalSpecifier => transformedSpecifier to allow users to filter and transform however they want

However, before doing (3) I would wait for someone to open an issue with a concrete use case.

Copy link
Member

Choose a reason for hiding this comment

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

extract the plugin to its own package, and when it's used directly allow passing a function originalSpecifier => transformedSpecifier to allow users to filter and transform however they want

We can even allow rewriteImportExtensions to pass in a function in the future.😉

}
},
},
};
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import "./a.ts";
import "./a.mts";
import "./a.cts";
import "a-package/file.ts";
// Bare import, it's either a node package or remapped by an import map
import "soundcloud.ts";
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"sourceType": "module",
"presets": [["typescript", { "rewriteImportExtensions": true }]]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import "./a.js";
import "./a.mjs";
import "./a.cjs";
import "a-package/file.js";
// Bare import, it's either a node package or remapped by an import map
import "soundcloud.ts";
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ describe("normalize options", () => {
"jsxPragmaFrag": "React.Fragment",
"onlyRemoveTypeImports": true,
"optimizeConstEnums": false,
"rewriteImportExtensions": false,
}
`);
});
Expand Down Expand Up @@ -96,6 +97,7 @@ describe("normalize options", () => {
"jsxPragmaFrag": "React.Fragment",
"onlyRemoveTypeImports": undefined,
"optimizeConstEnums": false,
"rewriteImportExtensions": false,
}
`);
});
Expand Down