Home >Web Front-end >Front-end Q&A >What are the three import methods in es6

What are the three import methods in es6

青灯夜游
青灯夜游Original
2022-05-19 17:59:252462browse

Method: 1. Pack all the variables exported in a file into an object and import it with the "import * as from "module"" statement; 2. Use the "import name it as you like from "module"" statement ;3. Use the "import {specified name} from "module"" statement.

What are the three import methods in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 import three import methods

import Name it arbitrarily from "module identifier"

This will only take effect if there is a default export export syntax in the module

// A.js
export default 20
// B.js
import A from './A'
上面的代码生效的前提是,只有在A.js中有默认导出的export default语法时才会生效。
这种不使用{}来引用模块的情况下,import模块的命名是随意的,即如下三种引用命名都是正确的:
//B.js
import A from './A'
import B from './A'
import Something from './A'
因为它总是会解析到A.js中默认的export default

import {specified name} from "module identifier"

It will only take effect if there is code in the module named export name with the specified name

//A.js
export const A = 21
//B.js
import { A } from './A'

代码生效的前提是,只有在模块A.js中有如下命名导出为A的export name的代码,
而且,在明确声明了命名导出后,那么在另一个js中使用{}引用模块时,import时的模块命名是有意义的,如下:
// B.js
import { A } from './A'                 // 正确,因为A.js中有命名为A的export
import { B } from './A'                 // 错误!因为A.js中没有命名为B的export

import * as from "module identifier" (packaged into an object )

Pack all the variables exported in a file into an object.
For example:

export const sqrt1 = Math.sqrt;
export const sqrt2= Math.sqrt;



import * as sqrtobj from "....."
sqrtobj.sqrt1
sqrtobj.sqrt2

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What are the three import methods in es6. 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