Basic
syntax
- In index.html, we must tell the browser that a script should be treated as a module, by using the attribute
<script type="module"> - Always
use strictand Each module has its own module-level scope. Onlyexportwhat they want to be accessible from outside andimportwhat they need. - Modules work only via HTTP(s), not in local files.
A module code is evaluated only the first time when imported
- All importers get exactly the one and only that export, so it’s shared between importers
import.meta
import.meta: contains the information about the current module.
this is undefined
Module <script>s are deferred
- Wait until the HTML document is fully ready.
async works on inline scripts
<script async type="module">: inline script has async doesn’t wait for anything.
- used for counters, ads, document-level event listeners…
Export and Import
import/exportstatements don’t work if inside{...}. As for importing conditionally, look at the Dynamic Imports part.
import
import *
- We can import everything as an object using
import * as <obj> from src.
import “as”
import {sayHi as hi, sayBye as bye} from './say.js' for brevity.
Export
- No semicolons after
export class/function - Technically we could put
exportabove functions declarations as well.export {sayHi, sayBye}; // a list of exported variables
export “as”
export {sayHi as hi, sayBye as bye}
export default
export default class User {} then we can import without curly braces, import User form './user.js'
- We can choose the name
UserormyUserwhen importing. But there is the convention that imported variables should correspond to file names. - At most one
default exportper file, so no name is fine because we don’t need to{name}. Import without curly braces knows what to import.
The “default” name
export {sayHi as default}is the same asexport default sayHiimport {default as User, sayHi} from './user.js': import the default export along with a named oneimport * as user from './user.js': if import everthing*, then thedefaultproperty is exactly the default exportlet User = user.default
Re-export
export...from...: allows to import things and immediately export them (possibly under another name)
- only named exports (not )
1 | // import login/logout and immediately export them |
Re-exporting the default export
We have to write export {default} from ..., for no named default.
- If we’d like to re-export both named and the default export, then two statements are needed:
export * from ...export {default} from ...
Dynamic Imports
- Dynamic imports work in regular scripts.
The import(module) expression
It can be like let {hi, bye} = await import('./say.js') or let {default: say} = await import('./say.js') if inside a async function.
- It’s not a function call, it’s a special syntax that just happens to use parentheses.