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-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM