Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created July 15, 2020 21:33
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 twolfson/b305f706b345c5f58597858717be9992 to your computer and use it in GitHub Desktop.
Save twolfson/b305f706b345c5f58597858717be9992 to your computer and use it in GitHub Desktop.
ES6 module passthrough import/export editing experimentation
// Load in our dependencies
import submodule from './submodule.js';
// Edit our pass-through content
// DEV: We can only modify mutable content on the submodule's keys
// If we attempt to replace a direct key, then the edit won't pass through
// submodule.bar = 'world'; // Works in this file, but doesn't pass through
submodule.bar.baz = 'hi';
// DEV: The following is a similarly acceptable way to pass-through edit
// This will still work with `export * from` for all keys, including those not imported
// import {bar} from './submodule.js';
// bar.baz = 'hi';
// Perform re-export
// https://stackoverflow.com/a/38077264
export * from './submodule.js';
// Loads from `export default submodule;`
import submodule from './submodule.js';
console.log(submodule);
// Loads from `export {foo, bar};`
import {foo, bar} from './submodule.js';
console.log(foo, bar);
// Demonstration of loading still working for pass-through alteration
// DEV: `import` seems to be hoisted to top so comment out this line to see alteration/no alteration
// import {foo as foo2, bar as bar2} from './alt-submodule.js';
// console.log(foo2, bar2);
{
"type": "module",
"name": "gist-es6-pass-through-import-export",
"version": "1.0.0",
"description": "Explore ES6 passthrough import/export",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Todd Wolfson <todd@twolfson.com> (http://twolfson.com/)",
"license": "Unlicense",
"dependencies": {},
"devDependencies": {}
}
const foo = "foo";
const bar = {"bar": "bar"};
// We can export an object or similar as the entire default `import`
// import submodule from './submodule.js';
const submodule = {foo, bar};
export default submodule;
// For called out key import, we need another format
// i.e. To use: import {foo, bar} from './submodule.js';
// We need an `export` call without `export default`
// Syntax doesn't allow exporting object
// export submodule;
// Instead must do explicit key export
export {foo, bar};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment