Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today we will learn about the modular system of ES6, how to export variables, functions, and classes from a module to be used in other modules.

In the module system of ES6, each JS file can be understood as a module, and the module code is executed in strict mode, so the variables and functions in the module are not added to the global scope.

Before ES6, we might need to use require.js for modular programming, and use commonJS specification for modular programming in Node.js. Js does not have a unified specification, so ES6 introduced a new modular solution.

Run it in a browser

Create a file message.js

export let message = 'ES6 Modules';
Copy the code

Message. js is a module in ES6 that contains a message variable that is exposed to other modules using the export statement.

Then we create app.js, where we import the message.js module, and in app.js we create an H1 element and insert it into the page.

The import statement is used to import the message variable from the message.js module.

import { message } from './message.js'

const h1 = document.createElement('h1');
h1.textContent = message

document.body.appendChild(h1)
Copy the code

Finally, create an HTML file and import app.js

<! DOCTYPEhtml>
<html>

<head>
  <meta charset="utf-8">
  <title>ES6 Modules</title>
</head>

<body>
  <script type="module" src="./app.js"></script>
</body>

</html>
Copy the code

Note: Here we need to add type=”module” to the script tag to introduce the app.js module. Run successfully as follows

Note: you need a local server to open the page, not directly use the local open file mode.

Export export

To export a variable, function, or class from a module, we need the export keyword

// log.js
export let message = 'Hi';

export function getMessage() {
  return message;
}

export function setMessage(msg) {
  message = msg;
}

export class Logger {}Copy the code

In the example above, we created the log.js module with 1 variable, 2 functions, and 1 class, and then we used export to export them.

It is important to note that functions or classes exported using export need to have names. We cannot export anonymous functions or classes using export.

We can also define variables or functions first and export them later

// foo.js
function foo() {
   console.log('foo');
}

function bar() {
  console.log('bar');
}
export foo;
Copy the code

In the above example, we first defined foo and then exported it later. Since we did not export bar, it is not accessible in other modules and can only be used in the current module, which we can call private.

The import import

Once you have a module with an export, you can use the import keyword to access variables, functions, or classes in another module

import { what, ever } from './other_module.js';
Copy the code

Specify the name of the variable, function, or class to import in curly braces.

Note: When we import the module, just as const variables are defined, what and ever are not allowed to change after they are introduced.

For example

// greeting.js
export let message = 'Hi';

export function setMessage(msg) {
  message = msg;
}
Copy the code

After we introduce the message variable and the setMessage() function, we can call the setMessage() function to change the value of the message variable in the module.

// app.js
import { message, setMessage } from './greeting.js';
console.log(message); // 'Hi'

setMessage('Hello');
console.log(message); // 'Hello' 
Copy the code

But if you modify the message variable directly, you get an error

message = 'Hallo'; // error
Copy the code

In fact, when we call setMessage(), JS will go to the greeting. JS module to execute the code and modify the message variable, and the imported message variable will change as well.

Import Imports multiple variables/functions

Export the A, b, result variables and the sum(), multiply() functions in cal.js

// cal.js
export let a = 10,
           b = 20,
           result = 0;

export function sum() {
  result = a + b;
  return result;
}

export function multiply() {
  result = a * b;
  return result;
}
Copy the code

Then import them in app.js and use them

// app.js
import {a, b, result, sum, multiply } from './cal.js';
sum();
console.log(result); / / 30

multiply();
console.log(result); / / 200
Copy the code

Import imports the entire module as an object

Following the example above, we can use the * keyword to import everything in the module as a single object

import * as cal from './cal.js';
Copy the code

You can then use CAL objects to access exported variables and functions

cal.a;
cal.b;
cal.sum();
Copy the code

import / exportThe limits of

Note that import/export statements can only be executed in the outermost layer of the code, not in other scopes. The following code will report syntax errors

const a = 10
if(true) {
   export a;
}
Copy the code

Likewise, the following import statement will report syntax errors

function importSum() {
   import { sum } from './cal.js';
}
Copy the code

The reason for the error is that ES6 import/export can only statically determine what to import or export, not dynamically import modules.

However, the import() function has been introduced in ES2020 to support dynamic import of modules.

Alias export/import

Next we export the add() function using the alias sum, using the as keyword, followed by the alias we want to export

// math.js  
function add( a, b ) {
   return a + b;
}

export { add as sum };
Copy the code

And then when we introduce modules, we’re going to use when we introduce add(), we’re going to use sum instead

import { sum } from './math.js';
Copy the code

If we do not want to use sum as the import, we can also use the as keyword to use another name

import {sum as total} from './math.js';
Copy the code

To export

Re-export the imported module

import { sum } from './math.js';
export { sum };
Copy the code

The following syntax is equivalent to the above

export { sum } from './math.js';
Copy the code

We can also re-export using aliases

export { sum as add } from './math.js';
Copy the code

Re-export all, we can use asterisks

export * from './cal.js';
Copy the code

For those of you who don’t know what this does, it actually does a lot of things, like if we have 20 components, and we don’t want to have 20 import statements, we just want to have 1 import statement, then we can create an intermediate file and import those 20 components and export them all, Then we can use an import statement, which can be written in the Ant Design component library.

Reference: / / https://github.com/vueComponent/ant-design-vue/blob/next/components/index.ts

import * as components from './components';
import { default as version } from './version';
export * from './components';
Copy the code

Anonymous import

Sometimes we’ll develop a module that doesn’t need to specify a name to import if we want to add a method to the native Array

// array.js
if (!Array.prototype.contain) {
  Array.prototype.contain = function(e) {
    // ...}}Copy the code

Next, we import the module directly and use the array’s contain method

import './array.js';
[1.2.3].contain(2); // true
Copy the code

The default is derived

A module can only have one default export. Generally speaking, the default export is easier to import because we do not need to look at the name of the imported variable, function or class. Generally speaking, if a module only has one export, we can use the default export.

The following sort.js module exports a function by default

// sort.js
export default function(arr) {
  // Sort the array
}
Copy the code

Use the sort.js module

import sort from './sort.js';
sort([2.1.3]);
Copy the code

The introduced sort is equivalent to the default function exported in the sort.js module.

Also, we can export other functions with default exports

// sort.js
export default function(arr) {
  // Sort the array
}
export function heapSort(arr) {
  / / heap sort
}
Copy the code

To import default and non-default exports from a module, follow these rules

  • First, the default export comes first
  • Other non-default exports are imported with curly braces

Such as this

import sort, { heapSort } from './sort.js';
sort([2.1.3]);
heapSort([3.1.2]);
Copy the code

If we wanted to alias the default export, we could also use the AS keyword, like this

import { default as quicksort, heapSort} from './sort.js';
Copy the code

conclusion

Today we learned all about JavaScript ES6 modular programming, so if you have any questions, leave a comment. I’ll see you tomorrow.

If this article is helpful, wechat search [xiaoshuai’s programming notes], let us progress every day