What to use to import resources in es6

青灯夜游
Release: 2022-04-19 19:48:33
Original
1416 people have browsed it

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

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}
Copy after login

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

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

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

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

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

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 = {}   //报错
Copy after login

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

Now, load this module.

// main.js

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

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

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

export default command

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

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

When other modules load the module,

importThe command can specify any name for the anonymous function

import cus from './export-default.js'
Copy after login

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

Compare normal output and default output

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

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

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

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<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;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><div class="contentsignin">Copy after login</div></div><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;
  });
Copy after login

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!

Related labels:
es6
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!