Skip to content

Instantly share code, notes, and snippets.

@davidhund
Created December 9, 2016 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhund/ace2ea64255df6e0f4f0afc548faf897 to your computer and use it in GitHub Desktop.
Save davidhund/ace2ea64255df6e0f4f0afc548faf897 to your computer and use it in GitHub Desktop.
Imported modules are always global?
/**
* ?????????????????????????????????????????????????????????????????????????
*
* - Using a MYMODULE (revealing module patter) as below
* - Processed with Rollup
*
* `import`ed `cfg()`, `msg()` and `debounce()` are *global*
*
* Q: as `import` may only appear in top-level:
* How can I have these functions scoped to MYMODULE?
*
*
* ????????????????????????????????????????????????????????????????????????? */
/**
* ES6 `import` dependancy modules
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
import cfg from './config.js';
import msg from './msg.js';
import debounce from './debounce.js';
/*
* MyModule specific functionality
* ========================================================================= */
/**
* MyModule object
* ========================================================================= */
const MYMODULE = (function(win, doc) {
/**
* initializes MYMODULE module
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
const onInit = function() {
msg('onInit(), called by `MYMODULE.init()`');
};
/**
* (DEBOUNCED!) Window Resize callback
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
const onDebouncedWinResize = debounce(function() {
msg('onDebouncedWinResize()');
}, 250);
// .. etc
/**
* 'Public' object, containing 'public' aliases of 'private' methods
* @type {Object}
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
const _public = {
init: onInit
};
return _public;
})(window, document);
/**
* RUN / Initialize as
* ========================================================================= */
MYMODULE.init();
@davidhund
Copy link
Author

davidhund commented Dec 9, 2016

So: I'm simply including <script src="mymodule.js"/> in the browser and now have global msg(), cfg() and debounce(), because mymodule imported 'em. What I (think I) want is to have these function in the local scope of mymodule…

If I remember correctly that's how CommonJS stuff worked: require() in the scope of mymodule would make required deps local...

Fixed

Note: the way I fixed this is to make MYMODULE a proper module that exports itself (and does not initialize). Then have a separate index.js which imports from mymodule.js and initializes it. Now msg() etc. are no longer global. Thanks @rikschennink and @kuvos. Also: rollup needs a iife format..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment