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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:49:53  来源:igfitidea点击:

Global require with Browserify v2

javascriptmodulebrowserify

提问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.json the HTML page itself. This is currently not possible because there is no requirefunction defined on the page.

我想使用 Browserify 来捆绑我的文件,但我随后需要将我的 Browserify 中的一个模块捆绑bundle.js在 HTML 页面本身上。这目前是不可能的,因为require页面上没有定义函数。

It appears that the requirefunction defined by browserify in bundle.jsis 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 requirein 定义的函数在bundle.jsIIFE 内部,所以我不能使用它。有没有可能把这个扔掉来代替 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.startfunction 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 -rto 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 appto expose require('app')to the external context.

在您的情况下,只需browserify -r app暴露require('app')于外部上下文即可。