“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Hello, I’m Shanyue.

Main refers to the entry file of NPM package. When we import a package, we actually import the file pointed to by the main field.

Main is a product of the CommonJS era and is the oldest and most commonly used entry file.

/ / package. Json content
{
  name: 'midash'.main: './dist/index.js'
}

// How to reference package
const midash = require('midash')

// The entry file is actually found through the main field, equivalent to the reference
const midash = require('midash/dist/index.js')
Copy the code

module

With the development of ESM and packaging tools, many packages will be packaged in N copies for distribution in modular format. For example, ANTD supports both ES and UMD, and will be packaged in two copies.

If the library is imported using import, the first look is for the module field to be introduced, otherwise the main field is introduced.

Based on this, many front-end friendly libraries are distributed as follows:

  1. Package the code in two formats:commonjses module
  2. moduleField ases moduleThe entrance
  3. mainField ascommonjsThe entrance
{
  name: 'midash'.main: './dist/index.js'.module: './dist/index.mjs'
}

// The following two are equivalent
import midash from 'midash'
import midash from 'midash/dist/index.mjs'
Copy the code

If your code only distributes a copy of the ES Module modularity scheme, place it directly in the main field.

exports

If the above two are swords, then exports must at least be Swiss Army knives.

Exports makes it easier to control access paths to subdirectories, also known as export Maps.

Suppose the directory of our Package is as follows:

├─ ├─ SRC ├─ ├─ ├─ download.txt ├─ ├─ download.txtCopy the code

Not inexportsThe module in the field cannot be referenced even if it accesses the path directly!

// package.json
{
  name: 'midash'.main: './index.js'.exports: {
    '. ': './dist/index.js'.'get': './dist/get.js'}}// It works fine
import get from 'midash/get'

// Does not work properly and cannot be imported
import get from 'midash/dist/get'
Copy the code

Exports can not only select different import files according to different modular schemes, but also import different import files according to environment variables (NODE_ENV) and running environment (nodeJS /browser/electron).