Modules

// By default anything that you declare in a file is not going to be visible outside, unless you export it. // Create module // user.js var localVariable = 123; // not visible outside this file export default function User(age) { this.age = age; }; // can be imported by other files // Use module // user-details.js import User from 'user'; var user = new User(24); // valid export default 1 export default NaN export default 'foo' export default { foo: 'bar' } export default ['foo', 'bar'] export default function foo () {} // error function foo () { export default 'bar' // SyntaxError } foo() // named exports export var foo = 'bar' export var baz = 'ponyfoo' // An important point to make is that ES6 modules export bindings, not values or references. // That means that a foo variable you export would be bound into the foo variable on the module, and its value would be subject to changes made to foo // It's better not to change the public interface of a module after it has initially loaded, though. // As seen in the snippet below, ES6 modules let you export lists of named top-level members. var foo = 'ponyfoo' var bar = 'baz' export { foo, bar } // or export { foo as ponyfoo } // or export { foo as default, bar } // Export best practices // use export default – and to do that at the end of your module files. var api = { foo: 'bar', baz: 'ponyfoo' } export default api // Import import _ from 'lodash' // Importing Named Exports import {map, reduce} from 'lodash' // alias import {cloneDeep as clone, map} from 'lodash' // mixed import {default, map} from 'lodash' import {default as _, map} from 'lodash' import _, {map} from 'lodash' // Import All The Things import * as _ from 'lodash'

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.