Javascript modules: Difference between revisions

From wikinotes
(Created page with "In recent years, javascript has been extended to support modules. = Documentation = <blockquote> {| class="wikitable" |- | MDN modules || https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules |- |} </blockquote><!-- Documentation --> = Example = <blockquote> <syntaxhighlight lang="bash"> </syntaxhighlight> <syntaxhighlight lang="html4strict"> <html lang="en"> <head> <script type="module" src="main.js"></script> <!-- add main.js to file --> </...")
 
No edit summary
Line 35: Line 35:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
</blockquote><!-- Example -->
= Exporting Symbols =
<blockquote>
== Exporting Default ==
<blockquote>
<syntaxhighlight lang="javascript">
// ${project}/modules/math.js
export default function sum(a, b) {
    return a + b;
}
</syntaxhighlight>
<syntaxhighlight lang="javascript">
import * as Math from './modules/math.js'
Math.default(1, 1) // -> 2  ('default' is the 'sum' function)
</syntaxhighlight>
</blockquote><!-- Exporting Default -->
</blockquote><!-- Exporting Symbols -->

Revision as of 20:52, 17 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

<html lang="en">
  <head>
    <script type="module" src="main.js"></script>   <!-- add main.js to file -->
  </head>
</html>
import * as Foo from './modules/foo.js'
import { Bar, Baz } from './modules/foo.js'
import { Bar as barbar } from './modules/foo.js'
export { foo, bar, baz };
export * from 'foo.js'
export { name } from 'foo.js'

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)