Skip to content

Instantly share code, notes, and snippets.

@kirbysayshi
Last active August 26, 2015 21:48
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 kirbysayshi/11b8c0c22fd23cff1238 to your computer and use it in GitHub Desktop.
Save kirbysayshi/11b8c0c22fd23cff1238 to your computer and use it in GitHub Desktop.
imports vs require

import is hoisted, meaning transition to import from require can be non-trivial if relying on app-wide dependencies to be initialized before use.

$ npm run import

> import-test@0.0.0 import /Users/drewp/GIT/import-test-gist
> babel-node index-import.js

exec a
exec c
exec b
default a from b
state { b: true }
b state: index? undefined
exec index
default a from index
state { b: true, index: true }
index state: index? true
$ npm run require

> import-test@0.0.0 require /Users/drewp/GIT/import-test-gist
> node index-require.js

exec index
exec a
default a from index
state { index: true }
index state: index? true
exec b
exec c
default a from b
state { index: true, b: true }
b state: index? true

The key difference being that state.index is undefined when importing because they are hoisted, vs true via require because it has time to initialize.

console.log('exec a');
function fn(from) {
fn.state[from] = true;
console.log('default a from ' + from);
console.log('state', fn.state);
}
fn.state = {};
export default fn;
console.log('exec a');
function fn(from) {
fn.state[from] = true;
console.log('default a from ' + from);
console.log('state', fn.state);
}
fn.state = {};
module.exports = fn;
console.log('exec b');
import blah1 from './a-import';
import blah3 from './c-import';
blah1('b');
const {index} = blah1.state;
console.log('b state: index?', index);
console.log('exec b');
var blah1 = require('./a-require');
var blah3 = require('./c-require');
blah1('b');
var index = blah1.state.index;
console.log('b state: index?', index);
console.log('exec c');
console.log('exec c');
console.log('exec index');
import blah1 from './a-import';
blah1('index');
const {index} = blah1.state;
console.log('index state: index?', index);
import blah2 from './b-import';
console.log('exec index');
var blah1 = require('./a-require');
blah1('index');
var index = blah1.state.index;
console.log('index state: index?', index);
var blah2 = require('./b-require');
{
"name": "import-test",
"version": "0.0.0",
"description": "playing around with imports vs CJS",
"main": "''",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"import": "babel-node index-import.js",
"require": "node index-require.js"
},
"author": "",
"license": "MIT",
"dependencies": {
"babel": "^5.8.21",
"browserify": "^11.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment