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

[core] Add exports field and build proper ES modules #745

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
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
1 change: 1 addition & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ module.exports = function getBabelConfig(api) {
mode: 'unsafe-wrap',
},
],
'babel-plugin-add-import-extension',
];

if (process.env.NODE_ENV === 'production') {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"babel-loader": "^9.2.1",
"babel-plugin-add-import-extension": "^1.6.0",
"babel-plugin-istanbul": "^6.1.1",
"babel-plugin-macros": "^3.1.0",
"babel-plugin-module-resolver": "^5.0.2",
Expand Down
7 changes: 6 additions & 1 deletion packages/mui-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"private": false,
"author": "MUI Team",
"description": "Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.",
"main": "./src/index.ts",
"keywords": [
"react",
"react-component",
Expand All @@ -26,9 +25,15 @@
"type": "opencollective",
"url": "https://opencollective.com/mui-org"
},
"exports": {
"./*": {
"import": "./src/*/index.ts"
}
},
"imports": {
"#test-utils": "./test/index.ts"
},
"type": "commonjs",
"scripts": {
"build": "pnpm build:node && pnpm build:stable && pnpm build:types && pnpm build:copy-files",
"build:node": "node ../../scripts/build.mjs node",
Expand Down
2 changes: 1 addition & 1 deletion packages/mui-base/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"moduleResolution": "bundler",
"noEmit": false,
"rootDir": "./src",
"outDir": "build"
"outDir": "build/types"
},
"include": ["src/**/*.ts*"],
"exclude": ["src/**/*.spec.ts*", "src/**/*.test.ts*"]
Expand Down
14 changes: 13 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 6 additions & 18 deletions scripts/build.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import childProcess from 'child_process';
import glob from 'fast-glob';
import path from 'path';
import { promisify } from 'util';
import yargs from 'yargs';
Expand Down Expand Up @@ -40,26 +39,11 @@ async function run(argv) {
'**/*.d.ts',
];

const topLevelNonIndexFiles = glob
.sync(`*{${extensions.join(',')}}`, { cwd: srcDir, ignore })
.filter((file) => {
return path.basename(file, path.extname(file)) !== 'index';
});
const topLevelPathImportsCanBePackages = topLevelNonIndexFiles.length === 0;

const outDir = path.resolve(
relativeOutDir,
// We generally support top level path imports e.g.
// 1. `import ArrowDownIcon from '@mui/icons-material/ArrowDown'`.
// 2. `import Typography from '@mui/material/Typography'`.
// The first case resolves to a file while the second case resolves to a package first i.e. a package.json
// This means that only in the second case the bundler can decide whether it uses ES modules or CommonJS modules.
// Different extensions are not viable yet since they require additional bundler config for users and additional transpilation steps in our repo.
//
// TODO v6: Switch to `exports` field.
{
node: topLevelPathImportsCanBePackages ? './node' : './',
stable: topLevelPathImportsCanBePackages ? './' : './esm',
node: './cjs',
stable: './esm',
}[bundle],
);

Expand Down Expand Up @@ -91,6 +75,10 @@ async function run(argv) {
throw new Error(`'${command}' failed with \n${stderr}`);
}

if (bundle === 'stable') {
await exec(`echo "{ \\"type\\": \\"module\\" }" > ${path.join(outDir, 'package.json')}`);
}

if (verbose) {
// eslint-disable-next-line no-console
console.log(stdout);
Expand Down
3 changes: 0 additions & 3 deletions scripts/copyFiles.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable no-console */
import path from 'path';
import {
createModulePackages,
createPackageFile,
includeFileInBuild,
prepend,
Expand Down Expand Up @@ -52,8 +51,6 @@ async function run() {
);

await addLicense(packageData);

await createModulePackages({ from: srcPath, to: buildPath });
} catch (err) {
console.error(err);
process.exit(1);
Expand Down
19 changes: 8 additions & 11 deletions scripts/copyFilesUtils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,22 +93,19 @@ export async function typescriptCopy({ from, to }) {

export async function createPackageFile() {
const packageData = await fse.readFile(path.resolve(packagePath, './package.json'), 'utf8');
const { nyc, scripts, devDependencies, workspaces, ...packageDataOther } =
const { imports, exports, nyc, scripts, devDependencies, workspaces, ...packageDataOther } =
JSON.parse(packageData);

const newPackageData = {
...packageDataOther,
private: false,
...(packageDataOther.main
? {
main: fse.existsSync(path.resolve(buildPath, './node/index.js'))
? './node/index.js'
: './index.js',
module: fse.existsSync(path.resolve(buildPath, './esm/index.js'))
? './esm/index.js'
: './index.js',
}
: {}),
exports: {
'./*': {
types: './types/*/index.d.ts',
import: './esm/*/index.js',
require: './cjs/*/index.js',
},
},
};

const typeDefinitionsFilePath = path.resolve(buildPath, './index.d.ts');
Expand Down