ES6 module commands: export and import

In front-end development, we will find a problem when we use import to introduce the required modules. Some need to use {} and some do not:

import { AUDIT } from './constants.js'
import tools from '@/utils/tools'

In fact, Xiaobai will be very confused about the module commands of the front-end ES6 for the first time. Let's talk about the module commands of ES6. After learning, we can answer the above questions.

Overview: the module loading schemes before ES6 mainly include CommonJS and AMD. However, both of them can only be loaded at run time and cannot be statically optimized at compile time. ES6 adds two module commands: export and import. The export command is used to specify the external interface of the module, and the Import command is used to input the functions provided by other modules.

modular

A module is a separate file. All variables inside the file cannot be obtained externally.

// constants.js
const AUDIT = {
    COLUMNS: [
        {
            title: 'Operator',
            dataIndex: 'operator'
        },
        {
            title: 'time',
            dataIndex: 'datetime'
        },
        {
            title: 'Operation type',
            dataIndex: 'operation'
        }
    ]
}

Here, constants.js is a module, and its variable AUDIT cannot be used by external acquisition at this time. If you want the external to be able to read the AUDIT variable in the constants.js module, you must use the export keyword to output the variable.

export command

The export command explicitly specifies the output code

// constants.js
export { AUDIT }

Here, the AUDIT constant is output externally with the export command.

In addition to the above, there is another way to write:

// constants.js
export const AUDIT = {
    COLUMNS: [
        {
            title: 'Operator',
            dataIndex: 'operator'
        },
        {
            title: 'time',
            dataIndex: 'datetime'
        },
        {
            title: 'Operation type',
            dataIndex: 'operation'
        }
    ]
}

In addition to outputting variables, the export command can also output functions or class es.

export function multiply (x, y) {
  return x * y
}

Output a function multiply.

Use of keyword as:

function v1() { ... }
function v2() { ... }

export {
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
}

The above code uses the as keyword to rename the external interfaces of functions v1 and v2. After renaming, v2 can be output twice with different names.

import command

After using the export command to define the external interface of the module, other JS files can load the module through the import command.

import { AUDIT } from './constants.js'

The above import command is used to load the constants.js file and get variables from it. The import command accepts a pair of braces that specify the variable names to be imported from other modules. The variable name in braces must be the same as the name of the external interface of the imported module (constants. JS).

be careful:
1. The variables entered by the import command are read-only and cannot be overwritten externally.

2. The from after import specifies the location of the module file, which can be a relative path or an absolute path. If there is no path but a module name, there must be a configuration file to tell the JavaScript engine the location of the module.

import { mapActions } from 'vuex'

export default command

The above describes export and import. We found that when using the Import command, we must know the variable name or function name in the module to be used, otherwise we cannot import. To solve this problem, you need to use the export default command to specify the default output for the module.

// settings.js
const list = {
    url: `/settings/`,
    method: 'get'
}

const add = {
    url: `/settings/`,
    method: 'post'
}
export default {
    list,
    add
}

When importing, you do not need to use {}, and you can specify any name customName for the variable:

import customName from './settings'

Note: the export default command is used to specify the default output of the module. Obviously, a module can only have one default output, so the export default command can only be used once. Therefore, the import command is not followed by the parenthesis, because it can only uniquely correspond to the export default command.

This explains the problem we encountered at the beginning. The introduction of tools does not require large quotation marks:

import tools from '@/utils/tools'
// tools.js
const tools = {
    /**
     * Judge whether the incoming value is empty
     * @param {Any} value value
     */
    isEmpty (value) {
        const dataType = checkDataType(value)
        let isEmpty
        switch (dataType) {
            case 'String':
                isEmpty = value === ''
                break
            case 'Array':
                isEmpty = !value.length
                break
            case 'Object':
                isEmpty = !Object.keys(value).length
                break
            default:
                isEmpty = false
        }
        return isEmpty
    },
    
    /*
      The object array is sorted by a key
    */
    compare (key) {
        return (a, b) => {
            const val1 = a[key]
            const val2 = b[key]
            return val1 - val2
        }
    }
}

export default tools

import() command

As mentioned earlier, the Import command is static, which is helpful for the compiler to improve efficiency, but it also makes it impossible to load modules at run time, so it cannot load on demand and conditional loading. To meet these two scenarios, we can use the import() function.

The import() function is equivalent to the require method in NODE, which returns a Promise object.

Example 1: load on demand

button.addEventListener('click', event => {
  import('./dialogBox.js')
  .then(dialogBox => {
    dialogBox.open();
  })
  .catch(error => {
    /* Error handling */
  })
});

In the above code, the import() method is placed in the listener function of the click event. This module will be loaded only after the user clicks the button.

Example 2: conditional loading

if (condition) {
  import('moduleA').then(...);
} else {
  import('moduleB').then(...);
}

Load different modules according to different situations.

Note: after import() loads the module successfully, the module will be used as an object as a parameter of the then method

Tags: Javascript

Posted on Tue, 23 Nov 2021 06:31:47 -0500 by sdat1333