Browserify插入全局变量 [英] Browserify insert global variable

查看:159
本文介绍了Browserify插入全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管存在很多相关问题,但它们并没有回答如何解决以下问题。

Despite there are a lot of relative questions, they do not answer how to resolve the following issue.

我有一个nodejs文件index.js。

I have a nodejs file index.js.

var browserify = require('browserify');

var data = getSomeData();
browserify('entry.js').bundle();

我想要以便可以访问数据 entry.js 中。我找到了browserify选项 insertGlobalVars ,但找不到任何适当的文档或示例。我尝试了 {insertGlobalVars:{myVar:someData}} ,但是它不起作用。

I want so that datacould be accessed in entry.js. I found browserify option insertGlobalVars but I could not find any proper documentation or examples. I tried {insertGlobalVars: {myVar: someData}} but it does not work.

我无法致电 require('someData')因为我的数据仅在执行 index.js 时产生。

I could not call require('someData') because my data is produced only when executing index.js.

更新
数据是一个数组;键是文件名,值-文件内容(大小约为500b)。

Update: Data is an array; key is a file name, value - file content (size is about 500b).

推荐答案

insertGlobalVars 选项采用包含函数的对象(使用 file basedir 参数调用)。因此,您必须像这样指定 insertGlobalVars 选项:

The insertGlobalVars option takes an object that contains functions (called with file and basedir arguments). So you would have to specify your insertGlobalVars option like this:

var browserify = require('browserify');
var someData = getSomeData();

browserify('entry.js', {
    insertGlobalVars: {
        someData: function () { return JSON.stringify(someData); }
    }
})
.bundle()
.pipe(process.stdout);

请注意,如果 someData 全局实际上是在代码中使用的。每个使用全局模块的模块都会收到自己的副本。

Note that the data will only be included in the bundle if the someData global is actually used in the code. And each module that uses the global will receive its own copy.

有可能在捆绑包中注入一个附加模块,从而可能需要数据(和捆绑包将仅包含数据的单个副本),但是由于 module-deps 与文件系统之间的交互,这将更加复杂。有关更多信息,您可以查看以下答案

It would be possible to inject an additional module into the bundle, so that the data could be required (and the bundle would contain only a single copy of the data), but that would be more complicated due to the interaction between module-deps and the file system. For more information, you could have a look at this answer.

这篇关于Browserify插入全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆