Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[ESM] Feature a distribution compatible with Node in "type": "module" #37335

@garronej

Description

@garronej

Steps to reproduce 🕹

Hi MUI team,

Steps to Reproduce:

You can reproduce the problem using the below repository:

git clone https://github.com/garronej/mui-import-esm  
cd mui-import-esm
yarn install
node index.mjs

Current behavior 😯

Node is unable to import MUI in the type: "module" environment.

We're getting Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/joseph/github/mui-import-esm/node_modules/@mui/material/styles' when importing any submodule of @mui/material.

Expected behavior 🤔

MUI should be correctly imported when running under Node's ESM environment.

Context 🔦

As the publisher of modules that depend on MUI, such as tss-react and onyxia-ui, I've encountered some problems with distributing real ECMAScript Modules (ESM) due to MUI's lack of a functional ESM distribution compatible with a "type": "module" node environment. While MUI does provide an ESM distribution that works with bundlers, it unfortunately fails to do the same for node.

Proposed Solutions:

To resolve the above issue, an additional entry to node_modules/@mui/material/package.json could potentially fix the problem:

  "exports": {
    "./styles": {
      "default": "./node/styles/index.js"
    },
    "./Button": {
      "default": "./node/Button/index.js"
    }
  }

Implementing this works for import { useStyles } from "@mui/material/styles" but doesn't function correctly for import Button from "@mui/material/Button". This issue arises as Button is represented as an object, rather than as the default function.

For the above scenario, there are two possible strategies:

  • Adopt @Andarist's Emotion strategy: Expose a .mjs file that reexports everything from the CommonJS ESModuleInterop distribution (See an example here). This strategy allows for correct defaults. And avoiding the dual package hazard. MUI also stands to gain nothing by being a real ESM, as it does not support lazy imports.

  • Publish a full, standards-compliant ESM distribution: Similar to tsafe.

The popularity of this comment based on its upvotes demonstrates that other developers are experiencing similar issues.

Regardless, I appreciate all the hard work done by the MUI team. Thank you!

Your environment 🌎

No response

Metadata

Metadata

Assignees

Labels

breaking changeIntroduces changes that are not backward compatible.scope: code-infraInvolves the code-infra product (https://www.notion.so/mui-org/5562c14178aa42af97bc1fa5114000cd).type: enhancementIt’s an improvement, but we can’t make up our mind whether it's a bug fix or a new feature.

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions