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

package.json中的main/module/browser #1

Open
tianyn1990 opened this issue Oct 21, 2019 · 0 comments
Open

package.json中的main/module/browser #1

tianyn1990 opened this issue Oct 21, 2019 · 0 comments

Comments

@tianyn1990
Copy link
Owner

tianyn1990 commented Oct 21, 2019

{
  "main": "lib/index",
  "module": "lib/index.mjs",
  "browser": {
    "./lib/index.js": "./lib/index.browser.js",
    "./lib/index.mjs": "./lib/index.browser.mjs"
  }
}

部分理解,正常来说main指向CJS,module指向ESM(mjs),当一个包兼容浏览器端与node端,但output不同时(比如同构应用),才使用 browser 指向兼容浏览器的版本,这种情况main和module两个都需要兼容版本,因此browser支持对象的格式提供一个映射关系。

目前node端应该只识别main字段;web端由webpack打包,可以通过指定target字段来声明打包环境(node、web..),遵循如下:

webpack

webpack/webpack#5673 (comment)

这里有webpack的部分代码(搜关键字 browser): https://github.com/webpack/webpack/blob/master/lib/WebpackOptionsDefaulter.js

webpack的模块选择优先级可以根据resolve.mainFields配置的顺序进行调整:https://webpack.docschina.org/configuration/resolve/#resolve-mainfields

要使用webpack的tree-shaking,需要通过ESM方式引入ESM规范的js,为了兼容不支持ESM的情况(比如node端),需要同时使用main和module

各种场景

SunshowerC/blog#8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant