|
| 1 | +import * as nodePath from "node:path"; |
| 2 | +import * as babel from "@babel/core"; |
| 3 | +import { addHook } from "pirates"; |
| 4 | +import { requireModuleSync } from "../../utils/module"; |
| 5 | + |
| 6 | +import type { NodePath, PluginObj, TransformOptions } from "@babel/core"; |
| 7 | + |
| 8 | +const STYLE_EXTESTION_RE = /\.(css|less|scss|sass|styl|stylus|pcss)$/; |
| 9 | +const IGNORE_STYLE_ERRORS = ["Unexpected token"]; |
| 10 | + |
| 11 | +export const TRANSFORM_EXTENSIONS = [".jsx", ".cjsx", ".mjsx", ".tsx", ".ctsx", ".mtsx"]; |
| 12 | +export const JS_EXTENSION_RE = /^\.([cm]?[tj]sx?|json)$/; |
| 13 | + |
| 14 | +export const setupTransformHook = (opts: { removeNonJsImports?: boolean } = {}): VoidFunction => { |
| 15 | + const transformOptions: TransformOptions = { |
| 16 | + browserslistConfigFile: false, |
| 17 | + babelrc: false, |
| 18 | + configFile: false, |
| 19 | + compact: false, |
| 20 | + presets: [require("@babel/preset-typescript")], |
| 21 | + sourceMaps: "inline", |
| 22 | + plugins: [ |
| 23 | + [ |
| 24 | + require("@babel/plugin-transform-react-jsx"), |
| 25 | + { |
| 26 | + throwIfNamespace: false, |
| 27 | + runtime: "automatic", |
| 28 | + }, |
| 29 | + ], |
| 30 | + require("@babel/plugin-transform-modules-commonjs"), |
| 31 | + ], |
| 32 | + }; |
| 33 | + |
| 34 | + const customIgnoreImportsPlugin = ({ types: t }: { types: typeof babel.types }): PluginObj => ({ |
| 35 | + name: "ignore-imports", |
| 36 | + visitor: { |
| 37 | + ImportDeclaration(path: NodePath<babel.types.ImportDeclaration>): void { |
| 38 | + const extname = nodePath.extname(path.node.source.value); |
| 39 | + |
| 40 | + if (extname && !extname.match(JS_EXTENSION_RE)) { |
| 41 | + path.remove(); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + requireModuleSync(path.node.source.value); |
| 47 | + } catch (err) { |
| 48 | + if (shouldIgnoreImportError(err as Error)) { |
| 49 | + path.remove(); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if ((err as NodeJS.ErrnoException).code === "ERR_REQUIRE_ESM") { |
| 54 | + mockEsmModuleImport(t, path); |
| 55 | + return; |
| 56 | + } |
| 57 | + } |
| 58 | + }, |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + if (opts.removeNonJsImports) { |
| 63 | + transformOptions.plugins!.push([customIgnoreImportsPlugin]); |
| 64 | + } |
| 65 | + |
| 66 | + const revertTransformHook = addHook( |
| 67 | + (originalCode, filename) => { |
| 68 | + return babel.transform(originalCode, { filename, ...transformOptions })!.code as string; |
| 69 | + }, |
| 70 | + { exts: TRANSFORM_EXTENSIONS }, |
| 71 | + ); |
| 72 | + |
| 73 | + return revertTransformHook; |
| 74 | +}; |
| 75 | + |
| 76 | +function shouldIgnoreImportError(err: Error): boolean { |
| 77 | + const shouldIgnoreImport = IGNORE_STYLE_ERRORS.some(ignoreImportErr => { |
| 78 | + return (err as Error).message.startsWith(ignoreImportErr); |
| 79 | + }); |
| 80 | + |
| 81 | + if (!shouldIgnoreImport) { |
| 82 | + return false; |
| 83 | + } |
| 84 | + |
| 85 | + const firstStackFrame = (err as Error).stack?.split("\n")[0] || ""; |
| 86 | + const filePath = firstStackFrame.split(":")[0]; |
| 87 | + const isStyleFilePath = STYLE_EXTESTION_RE.test(filePath); |
| 88 | + |
| 89 | + return isStyleFilePath; |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Replace esm module import with a Proxy. |
| 94 | + * Examples: |
| 95 | + * 1) `import pkg from "package"` -> `const pkg = new Proxy({}, {get: ..., apply: ...})` |
| 96 | + * 2) `import {a, b as c} from "package"` -> `const {a, c} = new Proxy({}, {get: ..., apply: ...})` |
| 97 | + */ |
| 98 | +function mockEsmModuleImport(t: typeof babel.types, path: NodePath<babel.types.ImportDeclaration>): void { |
| 99 | + const variableKey = genVarDeclKey(t, path.node); |
| 100 | + const variableValue = genProxy(t, [ |
| 101 | + t.objectExpression([]), |
| 102 | + t.objectExpression([genProxyGetHandler(t), genProxyApplyHandler(t)]), |
| 103 | + ]); |
| 104 | + |
| 105 | + const variableDecl = t.variableDeclaration("const", [t.variableDeclarator(variableKey, variableValue)]); |
| 106 | + |
| 107 | + path.replaceWith(variableDecl); |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * Generates the name of variables from the import declaration. |
| 112 | + * Examples: |
| 113 | + * 1) `import pkg from "package"` -> `pkg` |
| 114 | + * 2) `import {a, b as c} from "package"` -> `const {a, с} ` |
| 115 | + */ |
| 116 | +function genVarDeclKey( |
| 117 | + t: typeof babel.types, |
| 118 | + node: NodePath<babel.types.ImportDeclaration>["node"], |
| 119 | +): babel.types.Identifier | babel.types.ObjectPattern { |
| 120 | + if (node.specifiers.length === 1) { |
| 121 | + if (["ImportDefaultSpecifier", "ImportNamespaceSpecifier"].includes(node.specifiers[0].type)) { |
| 122 | + return t.identifier(node.specifiers[0].local.name); |
| 123 | + } |
| 124 | + |
| 125 | + return t.objectPattern([ |
| 126 | + t.objectProperty( |
| 127 | + t.identifier(node.specifiers[0].local.name), |
| 128 | + t.identifier(node.specifiers[0].local.name), |
| 129 | + false, |
| 130 | + true, |
| 131 | + ), |
| 132 | + ]); |
| 133 | + } |
| 134 | + |
| 135 | + const objectProperties = node.specifiers.map(spec => { |
| 136 | + return t.objectProperty(t.identifier(spec.local.name), t.identifier(spec.local.name), false, true); |
| 137 | + }); |
| 138 | + |
| 139 | + return t.objectPattern(objectProperties); |
| 140 | +} |
| 141 | + |
| 142 | +// Generates Proxy expression with passed arguments: `new Proxy(args)` |
| 143 | +function genProxy(t: typeof babel.types, args: babel.types.Expression[]): babel.types.NewExpression { |
| 144 | + return t.newExpression(t.identifier("Proxy"), args); |
| 145 | +} |
| 146 | + |
| 147 | +/** |
| 148 | + * Generates "get" handler for Proxy: |
| 149 | + * |
| 150 | + * get: function (target, prop) { |
| 151 | + * return prop in target ? target[prop] : new Proxy(() => {}, this); |
| 152 | + * } |
| 153 | + */ |
| 154 | +function genProxyGetHandler(t: typeof babel.types): babel.types.ObjectProperty { |
| 155 | + return t.objectProperty( |
| 156 | + t.identifier("get"), |
| 157 | + t.functionExpression( |
| 158 | + null, |
| 159 | + [t.identifier("target"), t.identifier("prop")], |
| 160 | + t.blockStatement([ |
| 161 | + t.returnStatement( |
| 162 | + t.conditionalExpression( |
| 163 | + t.binaryExpression("in", t.identifier("prop"), t.identifier("target")), |
| 164 | + t.memberExpression(t.identifier("target"), t.identifier("prop"), true), |
| 165 | + genProxy(t, [t.arrowFunctionExpression([], t.blockStatement([])), t.thisExpression()]), |
| 166 | + ), |
| 167 | + ), |
| 168 | + ]), |
| 169 | + ), |
| 170 | + ); |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Generates "apply" handler for Proxy: |
| 175 | + * |
| 176 | + * apply: function () { |
| 177 | + * return new Proxy(() => {}, this); |
| 178 | + * } |
| 179 | + */ |
| 180 | +function genProxyApplyHandler(t: typeof babel.types): babel.types.ObjectProperty { |
| 181 | + return t.objectProperty( |
| 182 | + t.identifier("apply"), |
| 183 | + t.functionExpression( |
| 184 | + null, |
| 185 | + [], |
| 186 | + t.blockStatement([ |
| 187 | + t.returnStatement( |
| 188 | + genProxy(t, [t.arrowFunctionExpression([], t.blockStatement([])), t.thisExpression()]), |
| 189 | + ), |
| 190 | + ]), |
| 191 | + ), |
| 192 | + ); |
| 193 | +} |
0 commit comments