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 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13582032.html
未经授权禁止转载,违者必究!