【Node】【6】模块系统

Node.js的模块系统基于CommonJS规范,其中每个文件被视为一个独立的模块,可以通过require函数引入其他模块,也可以通过module.exports将模块的功能暴露给外部。

CommonJS规范:使用 require() 函数来导入模块,使用 module.exports 或 exports 对象来导出模块。
ES Modules: 使用 import 和 export 关键字进行模块导入和导出。

【面试题】在低版本的 node 中想使用 es module 该如何做?【Nodejs】【出题公司: 腾讯】

  1. 低于Node 12 如何使用ES Modules:

    • 文件扩展名:在文件名后缀为 .mjs 的文件中使用 ES Modules。
    • package.json 配置:在 package.json 文件中添加 "type": "module"
    • 导入和导出:使用 importexport 语法。
    • 动态导入:动态导入可能不受支持。

    以下是一个示例:

    • 创建一个 app.mjs 文件:扩展文件格式

      // app.mjs
      import http from 'http';
      
      const server = http.createServer((req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello World\\n');
      });
      
      const PORT = 3000;
      
      server.listen(PORT, () => {
        console.log(`Server running at <http://localhost>:${PORT}/`);
      });
      
      
    • 修改 package.json 文件:

      {
        "type": "module", // 重点
        "scripts": {
          "start": "node --experimental-modules app.mjs"
        }
      }
      
      
    • 使用 -experimental-modules 标志运行应用程序:

      node --experimental-modules app.mjs
      
      
  2. 从 Node.js 12 开始,官方提供了对 ES Modules 的本机支持,无需额外配置即可使用 ES Modules。

module.exports 和 exports

//hello.js

exports.greet = function() {
    console.log('Hello World');
}
  • 这种方式是在 exports 对象上添加属性或方法,可以导出多个方法或属性。
  • 当引入这个模块时,返回的是 exports 对象,可以通过属性访问导出的方法或属性。
  • exports 则更适合在导出多个属性或方法时使用

//main.js


var Hello = require('./hello');

console.log(typeof Hello); //object exports对象

// let hello = new Hello();
Hello.greet();

//hello.js


// 导出一个构造函数 Hello
function Hello() {
    this.greet = function() {
        console.log('Hello, world!');
    };
}

module.exports = Hello;

  • 这种方式将整个模块(module.exports)替换为一个构造函数或对象。当引入这个模块时,返回的是整个构造函数(Hello)或对象。 不再是exports对象
  • 可以通过 new 关键字实例化 Hello,然后调用其方法。
  • 这种方式更加常用。可以导出对象。

//main.js

var Hello = require('./hello');

console.log(typeof Hello); //function

let hello = new Hello();
hello.greet();

模块导入

var http = require("http");// 内置模块
var express = require("express"); //第三方模块,通过npm安装和引入
var Hello = require('./hello');   // 文件模块 绝对路径和相对路径引入

在这里插入图片描述

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凭栏听雨客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值