Different main entry point in package.json for node and browser

杀马特。学长 韩版系。学妹 提交于 2019-12-05 03:31:49

It has been a long time since this question was asked. I just want to clarify the previous answer.

If you look at tools/webpack.config.js in React Starter Kit you will see that it exports two Webpack configurations that slightly differ, e.g. module.exports = [clientConfig, sererConfig]. The server-side bundle config has this field target set to node (by default it's web).

It seems this webpack heavior is not documented, but webpack automatically takes 'main' entry when target is 'node' and takes 'browser' entry when target is 'web'.

If you look at tools/webpack.config.js in React Starter Kit you will see that it exports two Webpack configurations that slightly differ, e.g. module.exports = [clientConfig, sererConfig]. The server-side bundle config has this field target set to node (by default it's web).

https://webpack.github.io/docs/configuration.html#target

The approach that you described works great for modules that have exactly the same API but different implementations, like in the case with HTTP client utility that uses XMLHttpRequest in its browser-specific implementation and Node's http module in its server implementation:

https://github.com/kriasoft/react-starter-kit/tree/master/src/core/fetch

The behavior is standardized here: https://github.com/defunctzombie/package-browser-field-spec

Although this specification is unofficial, many Javascript bundlers follow it, including Webpack, Browserify, and the React Native packager. The browser field not only allows you to change your module entry point, but to also replace or ignore individual files within your module. It's quite powerful.

Since Webpack bundles code for the web by default, you need to manually disable the browser field if you want to use Webpack for your server build. You can do that using the target config option to do this: https://webpack.js.org/concepts/targets/

user2849063

To have a different entry point for client and server in a Node Module, you can use process.browser flag and handle the same

if (process.browser) {
  // load client entry point
} else {
  // load server entry point
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!