Javascript es6 - 导入所有没有别名的命名模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34573779/
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
es6 - import all named module without alias
提问by Mr. Black
I know that we can import all named modules with alias as below,
我知道我们可以使用别名导入所有命名模块,如下所示,
import * as name from "module-name";
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Actually, I have re-exported my modules in A.js and the same is inherited in B.js. PFB. Now, it's two level of inheritance, so it's not a big deal to import the named modules. But, when I'm taking this to 5 level of inheritance (A -> B -> C -> D -> E), I need to import all named modules in all files and need to do the (re)export the same in all. Instead of doing this,
实际上,我已经在 A.js 中重新导出了我的模块,并且在 B.js 中继承了相同的模块。PFB。现在,它是两级继承,因此导入命名模块没什么大不了的。但是,当我将其提升到 5 级继承(A -> B -> C -> D -> E)时,我需要导入所有文件中的所有命名模块,并且需要执行(重新)导出相同的操作在所有。而不是这样做,
- Is there any other way to copy scope of all named modules into all level without reiterating the wheel (Import and Export)
- Behind the scene of this design is to make them to follow Opps concept and to avoid the redeclaration of the same modules.
- 有没有其他方法可以将所有命名模块的范围复制到所有级别而无需重复轮子(导入和导出)
- 这种设计的背后是让它们遵循 Opps 的概念,避免重新声明相同的模块。
A.js
js
import React from 'react';
import I18n from 'i18n-js';
import m1 from 'module1';
import m2 from 'module2';
export default class A extends React.Component {}
export {React, I18n, m1, m2)
B.js
js
import BaseComponent from './A';
import {React, I18n, m1, m2) from './A;
export default class B extends A {}
Is there any way to import all named modules without alias like import {*} from './A'
(instead of 2nd in B.js)
有没有办法导入所有没有别名的命名模块import {*} from './A'
(而不是 B.js 中的第二个)
回答by zerkms
Is there any way to import all named modules without alias like import {*} from './A' (instead of 2nd in B.js)
有没有办法导入所有没有别名的命名模块,比如 import {*} from './A' (而不是 B.js 中的第二个)
No.
不。
And the whole idea of re-exporting more than you need to save the "number of lines" in the final js file as you stated at
并且重新导出的整个想法超出了您在最终 js 文件中保存“行数”所需的数量,正如您在
Bcz, It's putting two lines for each import in the final js file. Consider If there are 10 import lines than, 20 lines will be added in final js. When you are thinking for production it will too cost
Bcz,它在最终的 js 文件中为每个导入放置了两行。考虑如果导入的行数超过 10 行,则最终 js 中将添加 20 行。当您考虑生产时,成本太高
Does not make much sense, since that's what JS minifiers are for.
没有多大意义,因为这就是 JS 缩小器的用途。
To summarise: one should not do that at the very first place:
总结一下:一开始就不应该这样做:
- You
export
only what you need to export - You
import
whatever you need wherever you need. - You use JS minifiers to optimise the output JS file size.
- 您
export
只需要导出的内容 import
无论您需要什么,您都可以随心所欲。- 您可以使用 JS 缩小器来优化输出 JS 文件的大小。
回答by Csaba Fityó
JavaScript solution:
JavaScript 解决方案:
import * as exports from 'foo';
Object.entries(exports).forEach(([name, exported]) => window[name] = exported);
Note:the imported wrapper object remains there.
注意:导入的包装对象保留在那里。
Node.js solution:
Node.js 解决方案:
Object.entries(require('foo')).forEach(([name, exported]) => global[name] = exported);
回答by einarmagnus
Here's a crazy experiment I did, that works, but it's probably dangerous in ways I don't fully understand. Would somebody explain to me why we don't do this?
这是我做的一个疯狂的实验,它有效,但它可能以我不完全理解的方式危险。有人会向我解释为什么我们不这样做吗?
var lodash = require("lodash");
function $localizeAll(name) {
return `eval("var " + Object.getOwnPropertyNames(${name}).reduce((code, prop)=>{
if (/^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(prop)) {
return code.concat(\`${prop} = ${name}["${prop}"]\n\`);
} else {
console.warn("did not import '" + prop + "'");
return code;
}
}, []).join(", ")+";")`
}
// this will make all exports from lodash available
eval($localizeAll("lodash"));
console.log(add(indexOf([1,2,6,7,12], 6), 5)); // => 7
It's a bit complicated as it evals in two levels, but it basically iterates of all the properties of an object with the given name in scope and binds all properties that have names qualified to be identifiers to an identifier by that name:
它有点复杂,因为它在两个级别进行 eval,但它基本上迭代具有给定名称的对象的所有属性,并将所有具有限定为标识符的名称的属性绑定到该名称的标识符:
var length = lodash["length"]
, name = lodash["name"]
, arguments = lodash["arguments"]
, caller = lodash["caller"]
, prototype = lodash["prototype"]
, templateSettings = lodash["templateSettings"]
, after = lodash["after"]
, ary = lodash["ary"]
, assign = lodash["assign"]
, assignIn = lodash["assignIn"]
, assignInWith = lodash["assignInWith"]
, assignWith = lodash["assignWith"]
, at = lodash["at"]
, before = lodash["before"]
, bind = lodash["bind"]
, bindAll = lodash["bindAll"]
, bindKey = lodash["bindKey"]
//...
, upperCase = lodash["upperCase"]
, upperFirst = lodash["upperFirst"]
, each = lodash["each"]
, eachRight = lodash["eachRight"]
, first = lodash["first"]
, VERSION = lodash["VERSION"]
, _ = lodash["_"]
;
There are some examples in this list of why this is a bad idea (e.g. it shadows arguments
).
这个列表中有一些例子说明为什么这是一个坏主意(例如它 shadows arguments
)。
You should be able to use this as follows (though you probably shouldn't like they say above).
您应该能够按如下方式使用它(尽管您可能不应该像上面所说的那样)。
B.js
js
import BaseComponent, * as extras from './A';
eval($localizeAll("extras"));
export default class B extends BaseComponent {}
Anyways, couldn't resist trying this out ;)
无论如何,无法抗拒尝试这个;)
回答by codelovesme
For Now, there is no clean way to do this. But you can overcome the problem by :
现在,没有干净的方法可以做到这一点。但是你可以通过以下方式克服这个问题:
1) defining an alias
1) 定义别名
import * as foo from "foo"
2) writing all modules
2)编写所有模块
import {a,b,c,d,...} from "foo"
回答by Ben Bucksch
global
is your current scope in node.js, similar to the window
object in the browser, so you can import into this object.
global
是你当前在 node.js 中的作用域,类似于window
浏览器中的对象,所以你可以导入到这个对象中。
To import all symbols from util module:
从 util 模块导入所有符号:
import * as util from "./util";
util.importAll(util, global);
In util.js:
在 util.js 中:
/**
* Takes all functions/objects from |sourceScope|
* and adds them to |targetScope|.
*/
function importAll(sourceScope, targetScope) {
for (let name in sourceScope) {
targetScope[name] = sourceScope[name];
}
}
... and a number of other functions like assert()
etc., which I need everywhere, and which should be part of the JavaScript language, but are not yet. But as others said, use this sparingly.
... 以及许多其他函数,如assert()
etc.,我在任何地方都需要它们,它们应该是 JavaScript 语言的一部分,但还没有。但正如其他人所说,请谨慎使用。