javascript Browserify v2 的全局需求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15456426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global require with Browserify v2
提问by substack
I want to use Browserify to bundle my files, but I then need to require one of the modules inside of my Browserify bundled bundle.js
on the HTML page itself. This is currently not possible because there is no require
function defined on the page.
我想使用 Browserify 来捆绑我的文件,但我随后需要将我的 Browserify 中的一个模块捆绑bundle.js
在 HTML 页面本身上。这目前是不可能的,因为require
页面上没有定义函数。
It appears that the require
function defined by browserify in bundle.js
is inside of an IIFE, so I can't use that. Is it possible to throw this one out in place of a global require
?
看起来browserify require
in 定义的函数在bundle.js
IIFE 内部,所以我不能使用它。有没有可能把这个扔掉来代替 global require
?
<script src="bundle.js"></script>
<script>
// Require the `app` module inside of `bundle.js`
var app = require('app');
app.start();
</script>
I need to do this because my app.start
function requires some JSON is passed to it which can only be rendered by the server-side template.
我需要这样做,因为我的app.start
函数需要向它传递一些 JSON,而这些 JSON 只能由服务器端模板呈现。
N.B. I am using Browserify v2.
注意我正在使用 Browserify v2。
回答by substack
You can use -r
to expose a global require()
function for the files you specify:
您可以使用-r
为您指定的文件公开一个全局require()
函数:
x.js:
x.js:
module.exports = function (n) { return n * 111 }
Console
安慰
$ browserify -r ./x.js > bundle.js
then in your html:
然后在你的 html 中:
<script src="bundle.js"></script>
<script>
var x = require('./x.js');
console.log(x(3))
</script>
will print 333
.
将打印333
。
In your case, just do browserify -r app
to expose require('app')
to the external context.
在您的情况下,只需browserify -r app
暴露require('app')
于外部上下文即可。