简体   繁体   English

如何在同一个变量下进行多次导入

[英]How to have multiple imports under a same variable

I want to organize my project imports with browserify so that I have a global utils variable from which I can call and execute functions much like jquery's $ . 我想用browserify组织项目导入,以便有一个全局utils变量,可以从其中调用和执行类似于jquery的$函数。

So in the end I want something like: 所以最后我想要的是:

window.utils = ...

So I can use utils.aFunction(); 所以我可以使用utils.aFunction();

I also want to divide my dependencies in several files, as an example, this would be my project: 我还想将依赖项分为几个文件,例如,这就是我的项目:

libs
  |_ math.js //Implements randomInt and RandomFloat methods
  |_ connection.js //Implements isConnected method
utils.js //Calls all the required dependencies

My idea so far is to have something like this: 到目前为止我的想法是这样的:

In libs/math.js : libs/math.js

module.exports = {
    randInt: function() {
        return 4;
    },
    randFloat: function() {
        return 4.1;
    }
};

And then I would do in utils.js : 然后我会在utils.js做:

var math = require('./libs/math');
var connection = require('./libs/connection');

var libs = [math, connection];

var utils = {};

for (var i = 0; i < libs.length; i++) {
    for (var key in libs[i]) {
        utils[key] = libs[i][key];
    }
}

window.utils = utils;

This actually works just fine, but I don't know if it wasn't already solved by a library. 这实际上可以正常工作,但是我不知道它是否还没有被库解决。

I have a feeling there are more efficient ways of doing this, what would be the recommended approach with browserify? 我觉得有更有效的方法可以做到这一点,在browserify中推荐的方法是什么?

The code for throwing things into util object is definitely odd looking, and I wouldn't recommend this looping over all your required util submodules. 将东西扔到util对象中的代码肯定看起来很奇怪,我不建议您在所有必需的util子模块上循环。

var libs = [math, connection];

var utils = {};

for (var i = 0; i < libs.length; i++) {
  for (var key in libs[i]) {
    utils[key] = libs[i][key];
  }
}

If you were using a common js approach with webpack/browserify, you would simply declare your util to be global in the configuration file, and simply add the needed module.exports inside of your util.js 如果您在webpack / browserify中使用通用的js方法,则只需在配置文件中声明util为全局文件,然后在util.js中添加所需的module.exports

//connect.js
  module.exports = {
    isConnected: function(){
        return true;
    }
};
//math.js
module.exports = {
    randInt: function() {
        return 4;
    },
    randFloat: function() {
        return 4.1;
    }
};
//utils.js
exports.math = require('./math');
exports.connect = require('./connect');
//test.js
var utils = require('./utils');
console.log(utils.math.randInt());
console.log(utils.connect.isConnected());

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

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