Table of Contents
import command
import()函数
Home Web Front-end Front-end Q&A What to use to import resources in es6

What to use to import resources in es6

Apr 19, 2022 pm 07:48 PM
es6

In es6, you can use the import statement or import() to import resources. The import command is used to import a specified module (resource file), with the syntax "import {member} from 'module identifier'"; import() is used to import files or modules, with the syntax "import (resource location)".

What to use to import resources in es6

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

Modular development can be carried out in es6, which is defined in the ES6 modular specification:

  • Each js file is an independent module

  • Use the import keyword to import other module members

  • Use the expost keyword to share module members externally

export command

##export

The module function mainly consists of two commands:

export and import. The export command is used to specify the external interface of the module, and the import command is used to import the functions provided by other modules.

A module is an independent file. All variables inside this file cannot be obtained from the outside. If you want the outside world to be able to read a variable inside the module, you must use the

export keyword to export the variable. For example:

//test1.js
export var firstName = 'mike'
export var lastName = 'Jack'

The above code is the

test1.js file, which saves user information. ES6 treats it as a module, which uses the export command to export three variables to the outside. In addition to the above, there is another way to write
export:

//test1.js
var firstName = 'mike'
var lastName = 'Jack'
export {firstName, lastName}

export In addition to outputting variables, the command can also output functions or classes

export function add(x, y){
    return x + y
}

exportThe command can appear anywhere in the module, as long as it is at the top level of the module. If it is in block-level scope, an error will be reported, as will the import command

as

Normally,

exportThe output variable is its original name, but it can be renamed using the as keyword

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

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

import command

After using the

export command to define the external interface of the module, other js files can load this module through the import command

import {firstName, lastName} from './test1.js'
console.log(firstName,lastName)

If you want to re-fetch the input variable Name, the

import command should use as to rename the input variable.

import {lastName as suName} from './test1.js'

importThe variables entered by the command are all read-only because its essence is an input interface. In other words, the interface is not allowed to be rewritten in the script that loads the module.

import {a} from './xxx'
a = {}   //报错

importThe from after it specifies the location of the module file. It can be a relative path or an absolute path. The .js suffix can be omit. If it is just the module name without a path, then there must be a configuration file to tell the JavaScript engine the location of the module

Overall loading of the module

In addition to specifying a certain output value to load, you can also use Load as a whole, that is, use an asterisk (*) to specify an object, and all output values ​​​​are loaded on this object.

The following is a

circle.js file, which outputs two methods area and circumference.

// circle.js
export function area(radius) {
  return Math.PI * radius * radius;
}

export function circumference(radius) {
  return 2 * Math.PI * radius;
}

Now, load this module.

// main.js

import { area, circumference } from './circle';
console.log('圆面积:' + area(4));
console.log('圆周长:' + circumference(14));

The above method is to specify the methods to be loaded one by one. The overall loading method is as follows.

import * as circle from './circle';
console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));

Note that the object where the module is loaded as a whole (the above example is

circle) should be statically analyzable, so runtime changes are not allowed. The following writing methods are not allowed.

import * as circle from './circle';

// 下面两行都是不允许的
circle.foo = 'hello';
circle.area = function () {};

export default command

export default is used to specify the default output for the module

//export-default.js
export default function(){
    console.log('foo')
}

When other modules load the module,

importThe command can specify any name for the anonymous function

import cus from './export-default.js'

export defaultThe command can be used before a non-anonymous function, but the function name is invalid outside the module. Loading When, it is loaded as an anonymous function. In essence, export default is to output a variable or method called default, and then the system allows you to give it any name

export default function test(){
    console.log('test')
}

Compare normal output and default output

//第一组
export function arc(){
    //...
} //输出

import {arc} from 'arc'  //输入

//第二组
export default arc2(){
    //...
}  //输出
import arc2 from 'arc2'   //输入

Summary: exportThe corresponding import statement needs to use curly brackets, export default The corresponding import statement does not require the use of braces. The export default command is used to specify the default output of the module. Obviously, a module can only have one default output, so export default is only allowed to be used once in the same module. Therefore, there is no need to add braces after the corresponding import command.

Combined writing method of export and import

If in a module, input first and then output the same module,

import# The ## statement can be written together with the export statement<pre class='brush:php;toolbar:false;'>export {foo, bar} from &amp;#39;my_module&amp;#39; //可以简单理解为 import {foo, bar} from &amp;#39;my_module&amp;#39; export {foo, bar}</pre><p>上面代码中,<code>exportimport语句可以结合在一起,写成一行。但需要注意的是,写成一行以后,foobar实际上并没有导入当前模块,只是相当于对外转发了这两个接口,导致当前模块不能直接使用foobar.

import()函数

import(specifier)

上面的代码中,import函数的参数specifier,指定所要加载的模块的位置。。import命令能够接受什么参数,import()函数就能接受什么参数,两者区别主要是后者为动态加载。

import()返回一个 Promise 对象。下面是一个例子。

const main = document.querySelector(&#39;main&#39;);
import(`./section-modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });

import()函数可以用在任何地方,不仅仅是模块,非模块的脚本也可以使用。它是运行时执行,也就是说,什么时候运行到这一句,就会加载指定的模块。另外,import()函数与所加载的模块没有静态连接关系,这点也是与import语句不相同。import()类似于 Node 的require方法,区别主要是前者是异步加载,后者是同步加载。

【相关推荐:javascript视频教程web前端

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

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
3 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

How to determine how many items there are in an array in es6 How to determine how many items there are in an array in es6 Jan 18, 2023 pm 07:22 PM

In ES6, you can use the length attribute of the array object to determine how many items there are in the array, that is, to get the number of elements in the array; this attribute can return the number of elements in the array, just use the "array.length" statement. Returns a value representing the number of elements of the array object, that is, the length value.

See all articles