Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - How do I exclude the "require('react')" from my Browserified bundle?

I'm using Browserify to bundle a ReactJS application.

All my components include a require("react") at the top. This causes Browserify to include the ReactJS source in my bundle. But I'd like to exclude it.

How do I do that? Is this the right thing to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...