JavaScript es module: necessary skills of modern front-end programming

Front end bee 2020-11-12 10:06:27
javascript es module necessary skills

since ES After the module is added to the specification ,JavaScript The module in is much simpler . Modules are separated by file , Load asynchronously . Export is to use export Keyword defined ; Value can be used import Keyword import .

Although the basics of importing and exporting individual values are very easy to master and use , But there are many other ways to use ES Modules to make your imports and exports work the way you want them to . In this paper , I'll show you all the ways you can export and import in modules .

One thing to remember is , Exports and static imports can only occur on the outermost layer of a module . You can't take a function 、if Statement or any other block to export or statically import . in addition , Dynamic import can be done in functions , We'll discuss it at the end of this article .


The default is derived

Each module has one " Default " export , It represents the main values exported by the module . There may be more derived values , But the default export value represents the definition of the module . There can only be one default export in a module .

const fruitBasket = new FruitBasket()
export default fruitBasket

Be careful , Before the default export , I have to define the value first . If I want to , I can also export my values immediately , Instead of assigning it to a variable , But then I can't export it and assign it to a variable .

We can export a function declaration and a class declaration by default , You don't have to assign it to a variable first .

export default function addToFruitBasket(fruit) {
// ...

We can even export literals as default .

export default 123

Named export

Any variable declaration can be exported at creation time , This will create a " Named export ", Use the variable name as the export name .

export const fruitBasket = new FruitBasket()

We can also immediately export the declaration of functions and classes .

export function addToFruitBasket(fruit) {
// ...
export class FruitBasket {
// ...

If we want to export a defined variable , We can use curly braces to wrap variable names as objects .

const fruitBasket = new FruitBasket()
export { fruitBasket }

We can even use as Keyword to rename our export , Make it different from the variable name . if necessary , We can also export other variables at the same time .

const fruitBasket = new FruitBasket()
class Apple {}
export { fruitBasket as basketOfFruit, Apple }

Aggregate export

We're going to have this kind of situation all the time , It's importing modules from a module , And then immediately export these values . Such as this :

import fruitBasket from './fruitBasket.js'
export { fruitBasket }

When you want to import and export many things at the same time , It can become cumbersome .ES Module allows us to import and export multiple values at the same time .

export * from './fruitBasket.js'

This will put ./fruitBasket.js All named exports are repackaged and exported again , But it doesn't export the default export values , Because a module can only have one default export value . If we want to import and export multiple modules with default export , Which value will be the default export value of the export module ?

We can specifically export default modules from other files , Or name the default export when re exporting .

export { default } from './fruitBasket.js'
// perhaps
export { default as fruitBasket } from './fruitBasket.js'

We can also selectively export different projects from another module , Instead of re exporting all the items . under these circumstances , We also use braces .

export { fruitBasket as basketOfFruit, Apple } from './fruitBasket.js'

Last , We can use as Keyword to package the entire module into a single named export . Suppose we have the following documents :

// fruits.js
export class Apple {}
export class Banana {}

Now we can package it into a separate export object , This object contains all named and default export objects .

export * as fruits from './fruits.js'
// { Apple: class Apple, Banana: class Banana }


The default import

When importing a default value , We need to give it a name . Since it's the default value , It doesn't matter what we name it .

import fruitBasketList from './fruitBasket.js'

We can also import all the exports at the same time , Including named export and default export . This will put all the exports into one object , And the default export will be given "default " The property name .

import * as fruitBasket from './fruitBasket.js'
// { default: fruitBasket }

Name import

We can import any named export by wrapping the name of the export with curly braces .

import { fruitBasket, Apple } from './fruitBasket.js'

We can also use as Keyword rename import .

import {fruitBasket as basketOfFruit, Apple} from './fruitBasket.js'

We can also mix named exports and default exports in the same import statement . The default exported content will be listed first , Then there's the named export in braces .

import fruitBasket, { Apple } from './fruitBasket.js'

Side effects are introduced

Sometimes a module does not export values , We just want to import the module in and execute it immediately . When importing such a module , There is no need to list any exported values in the file . This is known as ” side effect (side-effect)“ Import , It will execute the code in the module directly without providing any exported values .

import './fruitBasket.js'

Dynamic import

Sometimes we don't know the name of the file before we import it . Or we don't need to import a file until half of the code is executed , We can use dynamic import to import modules anywhere in the code . So it's called " dynamic ", Because the path of the import may be uncertain , It can be a string variable or a string expression , Unlike static import, it must be a string literal .

because ES Modules are asynchronous , So the module will not be available immediately . We have to wait for it to load before we can do anything about it . Because of that , Dynamic import will return a parsing module of Promise.

async function createFruit(fruitName) {
try {
const FruitClass = await import(`./${fruitName}.js`)
} catch {
console.error('Error getting fruit class module:', fruitName)
return new FruitClass()


ES The exported content can be a value ( Including variables and literal quantities ) It can also be the declaration of classes and functions , From the export mode can be divided into default export 、 Named exports and aggregate exports . According to different export methods , Import can be divided into default import 、 Name import 、 Side effect import and dynamic import . Both named export and import can use as Specify alias .​ Export and static import must be on the outermost layer of the file , Dynamic import can be done asynchronously in the function of the code .

本文为[Front end bee]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple