How do I exclude the “require('react')” from my Browserified bundle?

北战南征 提交于 2019-11-28 20:30:00

@NickTomlin gave this answer, but then deleted it.


You can use external:

browserify --external react src.js > dest.js

An example using the api:

var bundler = browserify('src.js');

bundler.external('react');
bundler.bundle();

This is a viable option. external requires another script to provide the module in a compatible way. You can produce such a script like this:

browserify -r react > react.js
env NODE_ENV=production browserify -r react | uglifyjs -m > react.min.js

And in HTML:

<script src="react.js"></script>
<script src="dest.js"></script>

dest.js is your code except react. react.js is just react and its dependencies.

Need more things external? Just add them in addition to react.

browserify -x react -x react-bootstrap src.js > dest.js
browserify -r react -r react-bootstrap > vendor.js

You could also do something like this in package.json

"browser": {"react": "./react-fake.js"}
// ./react-fake.js
try {
    module.exports = require('react');
} catch(e){
    module.exports = window.React;
}

And compile with -x react. This allows you to accept a -r react build, and fallback to a global React.

Sounds like you want to use browserify-shim.

In your package.json

"browserify-shim": {
    "react": "global:React"
},
"browserify": {
    "transform": [ "browserify-shim" ]
},
"dependencies": {
    "browserify-shim": "~3.2.0"
}

(untested). This section has more information.

I also wanted to do this, and found a possible solution.

From the browserify -h help:

--ignore, -i Replace a file with an empty stub. Files can be globs.

Just use the ignore feature.

browserify -i react -i react-dom ...

I also added react and react-dom as peer dependencies, cause in my case, the package can be imported in other packages builds.

You can also use the externals section in the webpack.config.js file. eg:-

externals: {
        // require('jquery') is loaded externally and avaliable as jQuery
        "jquery": "jQuery"
    }

See https://webpack.github.io/docs/library-and-externals.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!