Home Web Front-end JS Tutorial How to use import and export in node.js

How to use import and export in node.js

Jan 30, 2018 am 09:47 AM
export javascript node.js

Import and export are modular imports and exports in es6. Node.js does not support them at this stage. They need to be compiled through babel to turn them into modular code for node.js. (For the node.js module, please refer to other node.js modular articles) This article mainly introduces the detailed explanation of the use of import and export in node.js. The editor thinks it is quite good. Now I will share it with you and make it for everyone. refer to. Let’s follow the editor to take a look, I hope it can help everyone.

export exposure

Use export to expose methods, objects, strings, etc., as shown in the following code


//写法1
export var foo=function(){
  console.log(1);
}
//写法2
var bar ={a:"1",b:2};
export {bar};
//写法3
var baz='hello world';
export {baz as qux};
Copy after login

Then, after the above code is compiled by babel, it becomes executable node.js code, as follows


"use strict";
//标记这个模块是es的模块
Object.defineProperty(exports, "__esModule", {
  value: true
});
//写法1
var foo = exports.foo = function foo() {
  console.log(1);
};
//写法2
var bar = { a: "1", b: 2 };
exports.bar = bar;
//写法3

var baz = 'hello world';
exports.qux = baz;
Copy after login

We know after seeing the above code, es6 The export will be converted into the exposure method of exports in node.js.

import Import

Let’s look at how to write import. Let’s introduce the file xx.js where export is written above

The first way to write it


import {foo,qux} from './xx';
console.log(qux);
Copy after login

foo, qux are the attributes we expose in xx.js. There are three attributes exposed in xx.js: foo, bar, and qux , it can be seen that this writing method requires knowing the names of the attributes exposed in the imported file, and can be written as needed without enumerating all attributes.

Let’s take a look at the code compiled by babel:


'use strict';
var _ = require('./xx');
console.log(_.qux);
Copy after login

is a simple require method that introduces xx.js, so use In this way, we can introduce es6 modules or node.js modules.

Second way of writing


import * as xx from './xx';
console.log(xx.bar);
Copy after login

Here we still introduce xx.js, this way of writing will expose xx.js The attributes of are all assigned to the variable xx (actually, it is an alias for module.exports). After being compiled by Babel, it is as follows:


'use strict';
var _ = require('./xx');
var xx = _interopRequireWildcard(_);
function _interopRequireWildcard(obj) {
  //判断是node模块还是es模块
  if (obj && obj.__esModule) {
    return obj;
  }
  else {
    var newObj = {};
    if (obj != null) {
      for (var key in obj) { 
        if (Object.prototype.hasOwnProperty.call(obj, key)) 
         newObj[key] = obj[key];
      }
    }
  //兼容旧的babel编译
    newObj.default = obj;
    console.log(newObj);
    return newObj;
  }
}
console.log(xx.bar);
Copy after login

Seeing the above code, there is One determines whether it is a node module or an es module. This writing method is also compatible with es modules and node modules.

The third way of writing


import oo from './xx'
console.log(oo.bar);
Copy after login

In this way of writing oo is a random variable, which you may think at first glance It’s the same as the second way of writing, but it’s not. Let’s take a look at the compiled code:


'use strict';
var _ = require('./xx');
var _2 = _interopRequireDefault(_);
function _interopRequireDefault(obj) { 
 return obj && obj.__esModule ? obj : 
 { default: obj }; 
}
console.log(_2.default.bar);
Copy after login

In the last line, oo.bar is compiled into _2.default. bar, there is one more default, of course the bar here cannot be found, so this usage is not used to introduce the export attribute, but the export default mentioned below.

export default exposure and one-time exposure

I will summarize export and export default in other articles. Here we only talk about the usage of export default. Let’s look at the code. .


var foo=123;
export default foo;
Copy after login

After being compiled by babel


"use strict";
Object.defineProperty(exports, "__esModule", {
 value: true
});
var foo = 123;
exports.default = foo;
Copy after login

See that the last line of foo will be assigned to exports.default, so It just corresponds to the writing method of import oo from './xx', which will call the properties in default, so these two usages should be used accordingly. Since the value of the attribute will be assigned to exports.default, you can have the following usage


export default 123;
Copy after login


export default {foo:123};
Copy after login


export default function f(){}
Copy after login


export default function (){}
Copy after login

The above code is written separately, because export default can only be used once in a js. The reason is the same as using module.exports, except that you cannot write more than one, the following is also the case Wrong writing:


export default var foo=123; //错误
Copy after login

export default can also be used to expose classes. I won’t go into details here, they are all exposures.

Some other usages

Inheritance

This is module inheritance, which is actually a parent module introducing a child module. Then the exposed attributes of the sub-module are exposed:


export * from './xx';
Copy after login

After being compiled


##

'use strict';
Object.defineProperty(exports, "__esModule", {
 value: true
});
var _ = require('./xx');
Object.keys(_).forEach(function (key) {
 if (key === "default" || key === "__esModule") return;
 Object.defineProperty(exports, key, {
  enumerable: true,
  get: function get() {
   return _[key];
  }
 });
});
Copy after login

Pay attention to the following The sentence


if (key === "default" || key === "__esModule") return;
Copy after login

default attribute is not exposed to the outside world... This shows that using exports default in the xx.js file we imported is invalid. The alternative writing method is


export {default} from './xx';
Copy after login

The inherited writing method is often used to organize multiple modules, and is often used together with the introduction package mentioned below

Induction folder (Introduction package )

Many people don’t understand the following line of code


import * as o from './oo'; //oo是个文件
Copy after login

Why import can introduce a folder, please note that not all folders can be used, inside At least one file is index.js or a js with package.json and another name. Because there is index.js in the folder, this is not a folder but a node.js package (for more information, see node.js package article), import will be compiled by babel into require. require can refer to the package of the specified path. Therefore, import can import a folder. We can rely on index.js to export other file codes in the folder, for example:



//index.js
export * from './1';
export * from './2';
Copy after login
We can get the attributes exposed in 1.js and 2.js by importing the oo folder.

Summarize

Looking at the code compiled by babel, we can see that the usage of export and exports, module.exports and export default are similar. As for what to use and how to use it, it depends on personal preference.

Related recommendations:

Detailed explanation of the usage and difference between export import and export default in JavaScript ES6

The above is the detailed content of How to use import and export in node.js. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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 implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles