简体   繁体   English

使用browserify进行预处理?

[英]Preprocessing with browserify?

How can I preprocess a function call with browserify? 如何使用browserify预处理函数调用?

In a large js file, at one point, I need to pass a JSON object to a variable but this JSON object may only be created by a function call: 在一个大型的js文件中,我需要将一个JSON对象传递给一个变量,但是这个JSON对象可能只能通过一个函数调用来创建:

var myvar = Ractive.parse('mytemplate.html');

If I write this function call like so, this line of code is appeared in the bundle.js file as is. 如果我像这样写这个函数调用,这行代码就会出现在bundle.js文件中。 I simply want something like: 我只想要这样的东西:

var myvar = THIS_WILL_RUN_WHILE_BROWSERIFYING(Ractive.parse('mytemplate.html'));

so in bundle.js I expect to see something like: 所以在bundle.js我希望看到类似的东西:

var myvar = [{myobj:4},{x:1,y:2}];

How can I make this happen with browserify (with Gulp)? 如何使用browserify(使用Gulp)实现这一目标?

Browserify allows you to create custom transforms, there is a good example of how to create transforms at the following link. Browserify允许您创建自定义转换,有一个很好的示例,说明如何在以下链接创建转换。

https://github.com/substack/browserify-handbook#transforms https://github.com/substack/browserify-handbook#transforms

The example of doing a replace of the $CWD with process.cwd() , appeared to be a good starting point for the OP to create the transform required. 使用process.cwd()替换$CWD的示例似乎是OP创建所需转换的良好起点。

In case of potential future dead links, here is the example. 在潜在的未来死链接的情况下,这是一个例子。

var through = require('through2');

module.exports = function (file) {
    return through(function (buf, enc, next) {
        this.push(buf.toString('utf8').replace(/\$CWD/g, process.cwd()));
        next();
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM