javascriptwebpackmaterial-ui

How does Mui configure its exports without an `exports` property in the package.json?


In Mui's documentation here they recommend using

import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';

style imports instead of

import { Button, TextField } from '@mui/material';

The reason for this, as I understand it, is that that @mui/material style import will ultimately go through a barrel file - and bundlers like Webpack:

  1. May not be able to treeshake accurately for production bundles
  2. Will not treeshake for development bundles, giving slower development build times.

Webpack respects a exports property in the package.json (documentation here) to declare submodules accessed via @mui/material/Button style imports.

However, Mui doesn't actually appear to use these in their package.json

So how are these imports working?


Solution

  • It's standard node module resolution.

    If you examine the rest of the directories/files in the npm package, you'll note that there's no src/lib/dist like directories. Note also there's no files property in the package.json

    It's all

    Accordion/
      index.js
    AccordionActions/
      index.js
    ...
    index.js
    package.json
    

    The root index.js is what's referenced in the main property of the package.json - this is the barrel file strategy used in the @mui/material style imports.

    But the @mui/material/Button style imports are working just by referencing the directory and accessing the index file in it.

    Mui's build process must involve building to a completely seperate directory and then copying over the package.json, as opposed to selectively choosing a folder to publish with the files property.