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

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


posted @ 2020-08-29 13:56  xgqfrms  阅读(363)  评论(7编辑  收藏  举报