Home  >  Article  >  Web Front-end  >  How to use import in JavaScript?

How to use import in JavaScript?

不言
不言Original
2019-01-19 17:00:5919014browse

In ES6, How to use import in JavaScript? objects can be managed through modularization. Modularization can not only reuse functions, but also improve maintainability.

How to use import in JavaScript?

#import is the syntax used to import functions, objects, and initial values ​​exported from a module into another module.

As shown below

import {模块名称} from "需要导入模块的路径名"

How to use import?

This module has default module and named module.

We first load the default export module and the named export module

import {ModuleA, ModuleB} from "modules"; 
import Default from 'modules2';

In the first line, we import the two named modules named Module A and Module B from the modules file .

In the second line, we import the default module from the modules 2 file.

Execute module export

To export functions, objects, and primitive values ​​into modules, you need to use export.

Let’s look at a specific example

Export it as the default module

// alert.js
export default function () {
    alert("default module called!");
};

Named export

// utils.js
export function sum(x, y, z) {
    return x+y+z;
}
 
export function multiply(x, y) {
    return x*y;
}

We can export modules named sum and multiply.

You can use this function by calling the following

import { sum, multiply } from 'utils'; 
console.log(sum(1, 2, 3));
console.log(multiply(5, 8));

The execution result is as follows

->6
->40

This article ends here. For more exciting content, you can pay attention to php Chinese Other related column tutorials on the Internet! ! !

The above is the detailed content of How to use import in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn