Browserify bundle in browser with exports

自作多情 提交于 2019-12-13 02:38:28

问题


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

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