Reputation: 1527
I have a Namespacing.js with something like the following
(function(){
window.GlobalObject = {
foo : function() { console.log("bar"); }
}
})();
Then i have another 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.
At Namespacing.js i added at the end:
export default GlobalObject;
Then i tryed to import it in MyScript.js
import GlobalObject from "Namespacing"
But then my webpack gets me an error
[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 ?
Upvotes: 2
Views: 61
Reputation: 1074295
To switch to import
/export
, you can't just add exports
to your existing files, you need to change their structure (ever so slightly).
For instance, Namespacing.js would have either:
export const GlobalObject = {
foo : function() { console.log("bar"); }
};
...to export a named symbol 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.)
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).
Don't worry about the fact that it involves removing the IIFE; modules are inherently scoped, module code doesn't run at global scope.
Upvotes: 3