[英]Resolving Export / Imports
I have a Namespacing.js with something like the following 我有一个类似以下内容的Namespacing.js
(function(){
window.GlobalObject = {
foo : function() { console.log("bar"); }
}
})();
Then i have another MyScript.js 然后我有另一个MyScript.js
GlobalObject.newAttribute = { ... }
So i'm now bundling with webpack and i was tryng to use modules on this, but i couldnt manage to do so. 所以我现在与webpack捆绑在一起,我试图在此上使用模块,但是我无法做到这一点。
At Namespacing.js i added at the end: 我在Namespacing.js末尾添加了:
export default GlobalObject;
Then i tryed to import it in MyScript.js 然后我尝试将其导入MyScript.js
import GlobalObject from "Namespacing"
But then my webpack gets me an error 但是后来我的webpack给我一个错误
[14:58:44] GulpUglifyError: unable to minify JavaScript
Caused by: SyntaxError: Unexpected token: name (Kneat) (line: 1, col: 7, pos: 7)
Does any1 knows a good way of doing this export/import ? 有谁知道进行此导出/导入的好方法吗?
To switch to import
/ export
, you can't just add exports
to your existing files, you need to change their structure (ever so slightly). 要切换到
import
/ export
,您不能仅将exports
添加到现有文件中,您需要(略有更改)更改其结构。
For instance, Namespacing.js would have either: 例如,Namespacing.js将具有以下任一功能:
export const GlobalObject = {
foo : function() { console.log("bar"); }
};
...to export a named symbol GlobalObject
. ...导出命名符号
GlobalObject
。 That would be imported like this: 可以这样导入:
import { GlobalObject } from './Namespacing.js';
(You could use an as
clause if you wanted a different name locally in the importing module.) (如果要在导入模块中本地使用其他名称,则可以使用
as
子句。)
Or you could export that object as the default export: 或者,您可以将该对象导出为默认导出:
export default {
foo : function() { console.log("bar"); }
};
...and import it like this: ...并像这样导入它:
import GlobalObject from './Namespacing.js';
Note that in that case, you can use any name you want for GlobalObject
in the module in which you're importing it (no need for as as
clause). 请注意,在这种情况下,可以在要导入
GlobalObject
的模块中使用想要的名称作为GlobalObject
(不需要as
子句)。
Don't worry about the fact that it involves removing the IIFE; 不必担心删除IIFE的事实。 modules are inherently scoped, module code doesn't run at global scope.
模块具有固有的作用域,模块代码不能在全局范围内运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.