Javascript modules: Difference between revisions
From wikinotes
Line 50: | Line 50: | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
// symbols can be exported in one location | |||
export { foo, bar, baz }; | export { foo, bar, baz }; | ||
export | |||
export | // symbols can be exported at declaration. ex: | ||
export function foo() { ... }; | |||
export const number = 123; | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Exports --> | </blockquote><!-- Exports --> |
Revision as of 16:00, 18 December 2022
In recent years, javascript has been extended to support modules.
Documentation
MDN modules https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Example
<!-- index.html --> <html lang="en"> <head> <script type="module" src="main.js"></script> <!-- add main.js to file --> </head> </html>// main.js import * as Math from './modules/math.js' console.log(Math.sum(1, 2));// modules/math.js export function sum(a, b) { return a + b; }
Syntax
Imports
import * as Foo from './modules/foo.js' // exported symbols accessed on 'Foo' namespace import { Bar, Baz } from './modules/foo.js' // import exported 'Bar', 'Baz' into current namespace import { Bar as barbar } from './modules/foo.js' // import exported 'Bar' as symbol 'barbar' within current namespaceExports
// symbols can be exported in one location export { foo, bar, baz }; // symbols can be exported at declaration. ex: export function foo() { ... }; export const number = 123;
Exporting Symbols
Exporting Default
// ${project}/modules/math.js export default function sum(a, b) { return a + b; }import * as Math from './modules/math.js' Math.default(1, 1) // -> 2 ('default' is the 'sum' function)