Skip to content

Instantly share code, notes, and snippets.

@iyu88
Last active March 2, 2024 13:09
Show Gist options
  • Save iyu88/e8c8177869bc7938ccea8f9961358209 to your computer and use it in GitHub Desktop.
Save iyu88/e8c8177869bc7938ccea8f9961358209 to your computer and use it in GitHub Desktop.
[2024-03-02-javascript-module-system] Example code snippet
// [출처] express (https://github.com/expressjs/express)
/**
* @description 모듈을 내보낼 때
* @see https://github.com/expressjs/express/blob/master/index.js#L11
*/
module.exports = require('./lib/express');
/**
* @description 모듈을 불러올 때
* @see https://github.com/expressjs/express/blob/master/lib/express.js#L15
*/
var bodyParser = require('body-parser')
// module.js
exports.a = 'a';
exports.b = 'b';
exports.c = 'c';
// index.js
const cjsModule = require('./module');
cjsModule.a = 'z';
console.log(cjsModule); // {a: 'z', b: 'b', c: 'c'}
// [출처] backbone (https://github.com/jashkenas/backbone)
/**
* @description 모듈을 내보낼 때
* @see https://github.com/jashkenas/backbone/blob/master/backbone.js#L16
*/
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
root.Backbone = factory(root, exports, _, $);
});
/**
* @description 모듈을 불러올 때
* @see https://github.com/jashkenas/backbone/blob/master/backbone.js#L25
*/
var _ = require('underscore'), $;
// [출처] react (https://github.com/facebook/react)
/**
* @description 모듈을 내보낼 때
* @see https://github.com/facebook/react/blob/main/packages/react/index.js#L31
*/
export {
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
act,
Children,
Component,
// (...)
} from './src/ReactClient';
/**
* @description 모듈을 불러올 때
* @see https://github.com/facebook/react/blob/main/packages/react/src/ReactClient.js#L25
*/
import {Component, PureComponent} from './ReactBaseClasses';
// module.js
export let a = 'a';
export let b = 'b';
export let c = 'c';
// index.js
import * as esmModule from './module.js';
esmModule.a = 'z';
console.log(esmModule);
/**
* esmModule.a = 'z';
* ^
* TypeError: Cannot assign to read only property 'a' of object '[object Module]'
*/
// 1. ESM 환경에서 CJS 모듈을 불러올 때
import * as CJS from './cjs-module.js';
// 2. CJS 환경에서 ESM 모듈을 불러올 때
const ESM = require('./es-module');
// a.mjs
export const a = 'a';
export default a;
// b.mjs
import module1 from './a.js';
import * as module2 from './a.js';
console.log(module1); // 'a'
console.log(module2); // { default: 'a', a: 'a' }
// b.cjs
const module = require('/a');
console.log(module); // Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
// [출처] redux (https://github.com/reduxjs/redux)
/**
* @see https://github.com/reduxjs/redux/blob/master/package.json#L29
*/
{
// (...)
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/redux.d.ts",
"import": "./dist/redux.mjs",
"default": "./dist/cjs/redux.cjs"
}
},
// (...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment