ECMAScript
fleeting- External reference: https://tc39.es/ecma262/#realm
- External reference: https://tc39.es/ecma262/
Created by TC39
document at https://tc39.es/ecma262/ is the most accurate and up-to-date ECMAScript specification
Realm
Before it is evaluated, all ECMAScriptV code must be associated with a realm. Conceptually, a realm consists of a set of intrinsic objects, an ECMAScript global environment, all of the ECMAScript code that is loaded within the scope of that global environment, and other associated state and resources
.mjs extension
- External reference: https://tc39.es/ecma262/#sec-modules
ESM
- External reference: https://tc39.es/ecma262/#sec-modules
Before ES6 we really went out of our ways to obtain modules in JavaScript. Systems like RequireJS, Angular’s dependency injection mechanism, and CommonJS have been catering to our modular needs for a long time now – alongside with helpful tools such as Browserify and Webpack
ES6 modules have been heavily influenced by CommonJS
ES6 module system, strict mode is turned on by default. In case you don’t know what strict mode is, it’s just a stricter version of the language that disallows lots of bad parts of the language
CommonJS, you export values by exposing them on module.exports
could expose anything from a value type to an object, an array, or a function. module.exports = 1 module.exports = NaN module.exports = ‘foo’ module.exports = { foo: ‘bar’ } module.exports = [‘foo’, ‘bar’] module.exports = function foo () {}
mimic the CommonJS code we just saw by changing module.exports = into export default. export default 1 export default NaN export default ‘foo’ export default { foo: ‘bar’ } export default [‘foo’, ‘bar’] export default function foo () {}
export statements can only be placed at the top level in ES6 modules
CommonJS you don’t even have to assign an object to module.exports first. You could just tack properties onto it
module.exports.foo = ‘bar’ module.exports.baz = ‘ponyfoo’
export var foo = ‘bar’ export var baz = ‘ponyfoo’
ES6 modules export bindings, not values or references
ES6 modules let you export lists of named top-level members. var foo = ‘ponyfoo’ var bar = ‘baz’ export { foo, bar }
export something with a different name, you can use the export { foo as bar } syntax, as shown below. export { foo as ponyfoo }
for the most part I’d encourage you to use export default
will execute any code in the top level of the lodash module, though. import ’lodash’
CommonJS you’d import something using a require statement, like so. var _ = require(’lodash’)
import the default exported binding from an ES6 module, you just have to pick a name for it. The syntax is a bit different than declaring a variable because you’re importing a binding, and also to make it easier on static analysis tools. import _ from ’lodash’
add some braces and pick any named exports you want
import {map, reduce} from ’lodash’