xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js & ES Modules & Jest

Node.js & ES Modules & Jest

CJS & ESM

CommonJS

https://en.wikipedia.org/wiki/CommonJS

https://nodejs.org/api/modules.html#modules_modules_commonjs_modules

module wrapper

https://nodejs.org/api/modules.html#modules_the_module_wrapper

ES Modules

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

https://nodejs.org/api/esm.html#esm_modules_ecmascript_modules

Jest

ES5

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-08-0
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 */

const log = console.log;

const sum = (a = 0, b = 0) => {
  try {
    log(`a, b =`, a, b);
    return a + b;
  } catch (err) {
    throw new Error(`参数错误❌`, err);
  }
};


module.exports = sum;


const sum = require('./sum');
// const sum = require('./sum.js');

test('sum(1, 2) should return 3', () => {
  expect(sum(1, 2).toBe(3));
});


ES6

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-08-0
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 */

const log = console.log;

const sum = (a = 0, b = 0) => {
  try {
    log(`a, b =`, a, b);
    return a + b;
  } catch (err) {
    throw new Error(`参数错误❌`, err);
  }
};


export default sum;

export {
  sum,
};


import { sum } from "./sum";
// import { sum } from "./sum.mjs";

test('sum(1, 2) should return 3', () => {
  expect(sum(1, 2).toBe(3));
});



module.exports & exports

Node.js


https://www.w3schools.com/nodejs/nodejs_modules.asp

https://www.sitepoint.com/understanding-module-exports-exports-node-js/

https://tc39.es/ecma262/#sec-modules

https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js

https://github.com/xgqfrms-GitHub/node-express4-restful-api/issues/2

refs

https://flaviocopes.com/how-to-enable-es-modules-nodejs/

http://www.ruanyifeng.com/blog/2020/08/how-nodejs-use-es6-module.html



©xgqfrms 2012-2025

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @   xgqfrms  阅读(367)  评论(7编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-08-29 Observer & MutationObserver & IntersectionObserver & Proxy & Object.defineProperty()
2019-08-29 StackOverflow & xgqfrms All in One
2019-08-29 js & shallow copy & deep copy
2019-08-29 image to cur (cursor icons)
2019-08-29 VIE 架构
2019-08-29 如何使用 google cloud api 搭建服务接口
2018-08-29 Android File Transfer
点击右上角即可分享
微信分享提示