ReasonJun

Typescript : Module (CommonJS / ECMAScript Modules) 본문

Frontend/Typescript

Typescript : Module (CommonJS / ECMAScript Modules)

ReasonJun 2023. 6. 10. 14:44
728x90

In TypeScript, a module is a way to organize code into separate files and encapsulate its functionality. Modules allow you to define and export reusable pieces of code, such as classes, functions, interfaces, or variables, and import them in other parts of your program.

 

TypeScript supports two main module systems: CommonJS and ECMAScript (ES) modules.

  • CommonJS Modules:

CommonJS modules are primarily used in Node.js environments and follow the CommonJS specification. In CommonJS modules, you typically use require to import modules and module.exports or exports to export values. Here's an example:

// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
  add,
  subtract,
};

// app.js
const { add, subtract } = require('./math');

console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
  • ECMAScript (ES) Modules:

ECMAScript modules are a standard module system introduced in ES6 and are widely supported in modern browsers and JavaScript environments. In ES modules, you use import and export statements to work with modules. Here's an example:

// math.ts
export const add = (a: number, b: number): number => a + b;
export const subtract = (a: number, b: number): number => a - b;

// app.ts
import { add, subtract } from './math';

console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6

Note that to use ECMAScript modules, you need to specify the --module flag as es2020 or esnext in the TypeScript compiler configuration (tsconfig.json).

 

// If the D.TS file name is main.d.ts, add the code below.
/*
/// <reference path = "./main.d.ts"/>
>>> Triple-slash directive / Reference tag
*/

import _ from 'lodash'
// Module made of JavaScript requires a separate Type Declaration.
// lodash.d.ts

const str = 'the brown fox jumps over the lazy dog.'

console.log(_.camelCase(str))
console.log(_.snakeCase(str))
console.log(_.kebabCase(str)) // error
// lodash.d.ts file

declare module 'lodash' {
    interface Lodash {
        camelCase: (str: string) => string
        snakeCase: (str: string) => string
    }

    const _: Lodash
    export default _
}

// There is the same way as above, but it is difficult to specify a type every time.

// npm info @types/lodash >>> First identify the presence of existence.if there is
// npm i @types/lodash -D >>> This does not have to make this file.
728x90

'Frontend > Typescript' 카테고리의 다른 글

Typescript : additional provided types (Enum)  (0) 2023.06.17
Typescript : tsconfig.json  (0) 2023.06.10
Typescript : Generic  (0) 2023.06.10
Typescript : Class & Access Modifiers  (2) 2023.06.10
Typescript : Overloading  (0) 2023.06.10
Comments