Monday, January 5, 2015

Overview

Javascript’s new version (EcmaScript 6) has some amazing new features. The feature discussed in this post is the modules feature. Modules allow you to load functions from other js files and use them. In NodeJS, we use modules.exports to make a function or variable available to other files. The other files can then use require('moduleName') to access them. More information can be found here.

Details

Lets start out by creating a module cat that has 2 functions it exports: bite(victim) and lookCute()

cat.js

1
2
3
4
5
6
7
8
9
10
11
function bite(victim){
  return `*cat bit ${victim}*`;
  // notice the use of backtick and ${} for string templating
}

function distract(){
  return 'awww, that kitten is so cute';
}

// you can expose the function as is, or change the name
export { bite, distract as lookCute }

app1.js

1
2
import { lookCute } from 'cat';
console.log( lookCute() );

app2.js

1
2
3
import { bite, lookCute } from 'cat';
console.log( lookCute() );  // "awww, that kitten is so cute"
console.log( bite('Tom') ); // "*cat bit Tom*"

Examples

exporter1.js

1
2
3
4
5
6
7
8
export function blah(){
  return 'blah';
}

var aFunc = function(){
  console.log('does nothing');
}
export { aFunc }

importer1.js

1
2
3
import { blah, aFunc } from 'exporter1';
aFunc();
console.log( blah() );



exporter2.js

1
2
3
export default function(){
  return "this is all I'm exporting";
}

importer2.js

1
2
import randomName from 'exporter2';
randomName(); // when you import a default function, you choose the name

More examples of es6 modules can be found here.


Random Posts