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

How to use import in JavaScript?

不言
Release: 2019-01-19 17:00:59
Original
19079 people have browsed it

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 "需要导入模块的路径名"
Copy after login

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';
Copy after login

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!");
};
Copy after login

Named export

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

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));
Copy after login

The execution result is as follows

->6
->40
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template