【问题标题】:Import code inside client side js; in current scope, at any location在客户端js中导入代码;在当前范围内,在任何位置
【发布时间】:2017-03-09 19:36:23
【问题描述】:

假设我有两个文件 front.js 和 other.js。我需要在 front.js 中添加 other.js 的代码

front.js -

// blah
var obj= {
    a: function(){
        // more blah
    },

    b: function(){
        // more blah
    }, 

    /* 
    get 
    c: function(){ 
        // more blah 
    }, 
    here 
    */

    d: function(){
        // more blah
    }
};
// blah

其他.js -

c: function(){
    // more blah
},
// this ^^ is all that there is in the file (invalid js)

如何在front.js 的正确位置导入other.js 中的代码?

【问题讨论】:

  • c: 46, 是无效的 javascript,因此您无法命名文件 other.js。一种选择是使other.js 成为一个导出值的模块,然后在front.js 中引用它。但是您似乎需要即时组装js 代码,但是如果没有其他详细信息,很难说出您要做什么
  • c: 46,是无效的 js,是的,我知道。我正在查看一个具有不同 js 文件(不一定是有效的 js)的项目,如果将它们连接在一起,这将是有效的 js。想要在不制作大 js 文件或将不同文件重构为适当模块的情况下对其进行调试!

标签: javascript module scope


【解决方案1】:

这不是客户端模块加载器(甚至一般的模块系统,它依赖于有效的代码结构)会做的事情,而是 构建脚本 会做的事情。它只会扫描您的文件以查找 include 指令,并将它们逐字替换为引用文件的内容。有关将文件连接在一起的简单示例,请参阅 this answer。

【讨论】:

    【解决方案2】:

    感谢@Bergi,您的提示方向正确!

    我最终是这样做的:

    假设front.js是

    // blah
    var obj= {
        a: function(){
            // more blah
        },
    
        // other.js
    
        c: function(){
            // more blah
        }
    };
    // blah
    

    而 other.js 是 -

    b: function(){
        // more blah
    },
    


    用

    制作一个 app.js
    var bigstr= "", otherstr= "";
    var count= 0;
    
    var frontstream= fs.createReadStream("path/to/front.js");
    
    frontstream.on("data", function(chunk){
            bigstr+= chunk;
    });
    
    frontstream.on("error", function(error){
            console.log("front error");
    });
    
    frontstream.on("end", function(){
            var otherstream= fs.createReadStream("path/to/other.js");
    
            otherstream.on("data", function(chunk){
                    otherstr+= chunk;
            });
    
            otherstream.on("error", function(){
                    console.log("other error");
            });
    
            otherstream.on("end", function(){
                    count+= 1;
                    check();
            });
    });
    
    function check(){
            if(count===1){
                    bigstr= bigstr.replace("// other.js", otherstr);
    
                    fs.writeFile("path/to/newfront.js", bigstr, function(err){
                            if(!err){
                                    console.log("done");
                            }
                    });
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      相关资源
      最近更新 更多