-
-
Notifications
You must be signed in to change notification settings - Fork 32.3k
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
[code-infra] Babel plugin to fully resolve imported paths #43294
Changes from all commits
e26e204
a2e9fe3
0cf1f75
e3a9915
d8a432e
08785b3
399ffcc
a1cf4e8
8ceb06b
25bdc7d
d3574fd
e26fa02
70b8261
16bc6cd
3f5915c
73bb2ce
ff2c258
baa5247
6406fdb
fed743d
ef2d0fc
baa646d
7e2636d
0f21e37
7280c93
eb63fd3
d2c6ef5
28db8b7
86fae26
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
# @mui/internal-babel-plugin-resolve-imports | ||
|
||
A babel plugin that resolves import specifiers that are created under the Node.js resolution algorithm to specifiers that adhere to ESM resolution algorithm. | ||
|
||
See https://nodejs.org/docs/v20.16.0/api/esm.html#mandatory-file-extensions | ||
|
||
> A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (For example './startup/index.js') must also be fully specified. | ||
> | ||
> This behavior matches how import behaves in browser environments, assuming a typically configured server. | ||
|
||
This changes imports in the build output from | ||
|
||
```tsx | ||
// packages/mui-material/build/index.js | ||
export * from './Accordion'; | ||
|
||
// packages/mui-material/build/Breadcrumbs/BreadcrumbCollapsed.js | ||
import MoreHorizIcon from '../internal/svg-icons/MoreHoriz'; | ||
``` | ||
|
||
to | ||
|
||
```tsx | ||
// packages/mui-material/build/index.js | ||
export * from './Accordion/index.js'; | ||
|
||
// packages/mui-material/build/Breadcrumbs/BreadcrumbCollapsed.js | ||
import MoreHorizIcon from '../internal/svg-icons/MoreHoriz.js'; | ||
``` | ||
|
||
## options | ||
|
||
- `outExtension`: The extension to use when writing the output. Careful: if not specified, this plugin does not replace extensions at all, your bundles will likely be broken. We left this optional to allow for using this plugin together with the aliasing to source that we do everywhere. That way we can keep it in the pipeline even when not strictly necessary. | ||
Check warning on line 33 in packages-internal/babel-plugin-resolve-imports/README.md GitHub Actions / runner / vale
Check warning on line 33 in packages-internal/babel-plugin-resolve-imports/README.md GitHub Actions / runner / vale
Check warning on line 33 in packages-internal/babel-plugin-resolve-imports/README.md GitHub Actions / runner / vale
Check warning on line 33 in packages-internal/babel-plugin-resolve-imports/README.md GitHub Actions / runner / vale
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
// @ts-check | ||
/// <reference path="./resolve.d.ts" /> | ||
|
||
const nodePath = require('path'); | ||
const resolve = require('resolve/sync'); | ||
|
||
/** | ||
* @typedef {import('@babel/core')} babel | ||
*/ | ||
|
||
/** | ||
* Normalize a file path to POSIX in order for it to be platform-agnostic. | ||
* @param {string} importPath | ||
* @returns {string} | ||
*/ | ||
function toPosixPath(importPath) { | ||
return nodePath.normalize(importPath).split(nodePath.sep).join(nodePath.posix.sep); | ||
} | ||
|
||
/** | ||
* Converts a file path to a node import specifier. | ||
* @param {string} importPath | ||
* @returns {string} | ||
*/ | ||
function pathToNodeImportSpecifier(importPath) { | ||
const normalized = toPosixPath(importPath); | ||
return normalized.startsWith('/') || normalized.startsWith('.') ? normalized : `./${normalized}`; | ||
} | ||
|
||
/** | ||
* @typedef {{ outExtension?: string }} Options | ||
*/ | ||
|
||
/** | ||
* @param {babel} file | ||
* @param {Options} options | ||
* @returns {babel.PluginObj} | ||
*/ | ||
module.exports = function plugin({ types: t }, { outExtension }) { | ||
/** @type {Map<string, string>} */ | ||
const cache = new Map(); | ||
const extensions = ['.ts', '.tsx', '.js', '.jsx']; | ||
const extensionsSet = new Set(extensions); | ||
return { | ||
visitor: { | ||
ImportOrExportDeclaration(path, state) { | ||
if (path.isExportDefaultDeclaration()) { | ||
// Can't export default from an import specifier | ||
return; | ||
} | ||
|
||
if ( | ||
(path.isExportDeclaration() && path.node.exportKind === 'type') || | ||
(path.isImportDeclaration() && path.node.importKind === 'type') | ||
) { | ||
// Ignore type imports, they will get compiled away anyway | ||
return; | ||
} | ||
|
||
const source = | ||
/** @type {babel.NodePath<babel.types.StringLiteral | null | undefined> } */ ( | ||
path.get('source') | ||
); | ||
|
||
if (!source.node) { | ||
// Ignore import without source | ||
return; | ||
} | ||
|
||
const importedPath = source.node.value; | ||
|
||
if (!importedPath.startsWith('.')) { | ||
// Only handle relative imports | ||
return; | ||
} | ||
|
||
if (!state.filename) { | ||
throw new Error('filename is not defined'); | ||
} | ||
|
||
const importerPath = state.filename; | ||
const importerDir = nodePath.dirname(importerPath); | ||
// start from fully resolved import path | ||
const absoluteImportPath = nodePath.resolve(importerDir, importedPath); | ||
|
||
let resolvedPath = cache.get(absoluteImportPath); | ||
|
||
if (!resolvedPath) { | ||
// resolve to actual file | ||
resolvedPath = resolve(absoluteImportPath, { extensions }); | ||
|
||
if (!resolvedPath) { | ||
throw new Error(`could not resolve "${importedPath}" from "${state.filename}"`); | ||
} | ||
|
||
const resolvedExtension = nodePath.extname(resolvedPath); | ||
if (outExtension && extensionsSet.has(resolvedExtension)) { | ||
// replace extension | ||
resolvedPath = nodePath.resolve( | ||
nodePath.dirname(resolvedPath), | ||
nodePath.basename(resolvedPath, resolvedExtension) + outExtension, | ||
); | ||
} | ||
|
||
cache.set(absoluteImportPath, resolvedPath); | ||
} | ||
|
||
const relativeResolvedPath = nodePath.relative(importerDir, resolvedPath); | ||
const importSpecifier = pathToNodeImportSpecifier(relativeResolvedPath); | ||
|
||
source.replaceWith(t.stringLiteral(importSpecifier)); | ||
}, | ||
}, | ||
}; | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"name": "@mui/internal-babel-plugin-resolve-imports", | ||
"version": "1.0.16", | ||
"author": "MUI Team", | ||
"description": "babel plugin that resolves import specifiers to their actual output file.", | ||
"main": "./index.js", | ||
"exports": { | ||
".": "./index.js" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/mui/material-ui.git", | ||
"directory": "packages-internal/babel-plugin-resolve-imports" | ||
}, | ||
"license": "MIT", | ||
"scripts": {}, | ||
"dependencies": { | ||
"resolve": "^1.22.8" | ||
}, | ||
"devDependencies": { | ||
"@types/resolve": "^1.20.6", | ||
"@types/babel__core": "^7.20.5" | ||
}, | ||
"peerDependencies": { | ||
"@babel/core": "7" | ||
}, | ||
"publishConfig": { | ||
"access": "public" | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
declare module 'resolve/sync' { | ||
import { Opts } from 'resolve'; | ||
|
||
function resolve(id: string, options?: Opts): string; | ||
export = resolve; | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's unusual initial version ;)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
😄 I copied the
package.json
of@mui/internal-scripts
and didn't give it any further thought.