Wang's blog Wang's blog
首页
  • 前端文章

    • HTML教程
    • CSS
    • JavaScript
  • 前端框架

    • Vue
    • React
    • VuePress
    • Electron
  • 后端技术

    • Npm
    • Node
    • TypeScript
  • 编程规范

    • 规范
  • 我的笔记
  • Git
  • GitHub
  • VSCode
  • Mac工具
  • 数据库
  • Google
  • 服务器
  • Python爬虫
  • 前端教程
更多
收藏
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Wang Mings

跟随大神,成为大神!
首页
  • 前端文章

    • HTML教程
    • CSS
    • JavaScript
  • 前端框架

    • Vue
    • React
    • VuePress
    • Electron
  • 后端技术

    • Npm
    • Node
    • TypeScript
  • 编程规范

    • 规范
  • 我的笔记
  • Git
  • GitHub
  • VSCode
  • Mac工具
  • 数据库
  • Google
  • 服务器
  • Python爬虫
  • 前端教程
更多
收藏
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • git命令使用
  • nodejs如何同时支持import和require
  • nodejs使用说明
  • Electron跨平台开发笔记
  • JavaScript笔记
  • 常用的ES5和ES6中对象的导出和导入的差异之处
  • theme-vdoing-blog博客静态编译问题
  • 笔记
wangmings
2022-07-19

nodejs如何同时支持import和require

JavaScript 现在有两种模块。一种是 ES6 模块,简称 ESM;另一种是 CommonJS 模块,简称 CJS。
CommonJS 模块是 Node.js 专用的,与 ES6 模块不兼容。语法上面,两者最明显的差异是,CommonJS 模块使用require()和module.exports,ES6 模块使用import和export。
ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS 和 AMD 模块,都只能在运行时确定这些东西。
如何让require 和 import在同一文件中使用

  1. npm init -y 会默认生成一个package.json
    
  2. 在package.json这种添加 type :'module'  
    

一旦设置了以后,该项目的 JS 脚本,就被解释成 ES6 模块。

index.js

    // 调用
    
    // ES6 模块需要支持静态代码分析,而 CommonJS 模块的输出接口是module.exports,是一个对象,无法被静态分析,所以只能整体加载。
    import  lib from './lib.cjs'
    import * as newLib from './newLib.js'
    
    console.log(lib.count) // 3
    lib.incCounter();
    console.log(lib.count) // 3
    
    console.log(newLib.count) // 3
    newLib.incCounter();
    console.log(newLib.count) // 4
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14

lib.cjs

    ES5

    let count = 3;
    
    function incCounter(){
        return count++;
    }
    
    module.exports  = {
        count,
        incCounter
    }
1
2
3
4
5
6
7
8
9
10
11
12

newLib.js

    
    ES6
    let count = 3;
    
    function incCounter(){
        return count++;
    }
    
    export  {
        count,
        incCounter
    }
1
2
3
4
5
6
7
8
9
10
11
12

如果这时还要使用 CommonJS 模块,那么需要将 CommonJS 脚本的后缀名都改成.cjs。则.js脚本会被解释成 CommonJS 模块。

  • CommonJS 模块是 Node.js 专用的,与 ES6 模块不兼容。语法上面,两者最明显的差异是,CommonJS 模块使用require()和module.exports,ES6 模块使用import和export。
  • 它们采用不同的加载方案。从 Node.js v13.2 版本开始,Node.js 已经默认打开了 ES6 模块支持。

Node.js 要求 ES6 模块采用.mjs后缀文件名。也就是说,只要脚本文件里面使用import或者export命令,那么就必须采用.mjs后缀名。Node.js 遇到.mjs文件,就认为它是 ES6 模块,默认启用严格模式,不必在每个模块文件顶部指定"use strict"。

编辑 (opens new window)
git命令使用
nodejs使用说明

← git命令使用 nodejs使用说明→

最近更新
01
theme-vdoing-blog博客静态编译问题
09-16
02
搜索引擎
07-19
03
友情链接
07-19
更多文章>
Theme by Vdoing | Copyright © 2019-2025 Evan Xu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
  • 主题模式