问题
How do I access the exports from a Browserify bundle in the browser? Example:
// parser.js
exports.parse = parse;
Then I'm running
browserify lib/parser.js -o www/bundle.js
Every tutorial/readme I find ends with Drop a single <script> tag into your html and you're done!
<script src="bundle.js"></script>
But how do I run parse? The function require isn't defined in the browser.
var Parser = require('parser');
Parser.parse('hit kommer vi aldrig');
> Uncaught ReferenceError: require is not defined
回答1:
Browserify gives all your code a seperate scope to prevent pollution with global variables. You should make your parser global to access it in the browser.
Put this into your parser.js:
global.parse = parse;
回答2:
I found a way with requirejs. Instead of <script src="bundle.js"></script>, I use the code below.
requirejs(['bundle'], function(Parser) {
Parser.parseText('text');
// This is also where you would put angular.bootstrap()
});
来源:https://stackoverflow.com/questions/30582996/browserify-bundle-in-browser-with-exports