ts project๋ฅผ ์คํ์ํฌ ๋, ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋ฌ๋ค.
(node:27135) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
esmodule์ ์ฌ์ฉํ๊ธฐ ์ํด ์ถ๊ฐ์ ์ธ ์ค์ ์ด ํ์ํ๋ค. ์์นญํด๋ณธ ๊ฒฐ๊ณผ tsconfig.json์์ module์ commonjs๋ก ๋ฐ๊พธ์ด์ ํด๊ฒฐํ ์ ์์๋ค.
์ด์ฐธ์ tsconfig.json์์ module์ ์ค์ ํ๋ฉด ์ปดํ์ผ๋ฌ๊ฐ ๋ฌด์์ ํด์ฃผ๋์ง๋ฅผ ํ์ ํด๋ณด์๋ค.
- tsconfig.json ํ์ผ์ด ์์นํ๋ ๊ณณ์ด ํ์ ์คํฌ๋ฆฝํธ ํ๋ก์ ํธ์ ๋ฃจํธ์์ ๋ํ๋ธ๋ค.
- tsconfig.json์ typescript ์ปดํ์ผ๋ฌ ์ค์ ์ ํ ์ ์๋ค.
tsconfig.json์์ compilerOption์ ์ ํ ์ ์๋ค. compilerOption์ ์ปดํ์ผ๋ฌ ์ต์ ์์ ๋ง์ ํ์ ์คํฌ๋ฆฝํธ ์ค์ ์ ํ ์ ์๊ณ , ํ์ ์คํฌ๋ฆฝํธ๊ฐ ์ด๋ป๊ฒ ๋์ํด์ผ ํ๋์ง๋ฅผ ๋ค๋ฃฌ๋ค.
-
tsconfig.json
```json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true, // d.ts ํ์ผ ์์ฑ ์ฌ๋ถ
...
}
}
### Module
- ํ๋ก๊ทธ๋จ์ ๋ชจ๋ ์์คํ
์ ์ค์ ํ๋ค.
- "module"์ ์ค์ ํ๋ ๊ฒ์ moduleResolution์ ์ํฅ์ ์ค๋ค.
Module์ ํ์ฌ ํ๋ก์ ํธ๊ฐ esmodule ์์คํ
์ ์ฌ์ฉํ๋์ง๋ฅผ ๋ํ๋ด๋๊ฒ ์๋๊ณ , ์ปดํ์ผ๋ ๊ฒฐ๊ณผ๊ฐ ์ด๋ค ๋ชจ๋ ์์คํ
์ผ์ง๋ฅผ ์ค์ ํ๋ค.
๋ค์๊ณผ ๊ฐ์ ts ํ์ผ์ ์ค์ ๋ module system์ ๋ชฉํ๋ก ํ์ฌ ์ปดํ์ผ๋๋ค.
```typescript=
// @showEmit
// @module: commonjs
// @noErrors
import { valueOfPi } from "./constants";
export const twoPi = valueOfPi * 2;
- CommonJS
-
๋ชจ๋ ์ ์๋ exports ๊ฐ์ฒด๋ฅผ ์ด์ฉํ๊ณ , ๋ชจ๋ ์ฌ์ฉ์ require ํจ์๋ฅผ ์ด์ฉํ๋ค.
-
node.js ์๋ฒ์์๋ ๋ชจ๋ ์์คํ ์ ์ฌ์ฉํ๊ธฐ ์ํด ๋ง๋ค์ด์ง ๋ชจ๋ ์์คํ ์ด๋ค.
-
CJS์ ๋์ ๋ฐฉ์
require()๊ฐ ๋๊ธฐ์ ์ด๋ค; ํ๋ผ๋ฏธ์ค๋ฅผ ๋ฆฌํดํ๊ฑฐ๋, ์ฝ๋ฐฑ์ ํธ์ถํ์ง ์๋๋ค. require()๊ฐ ๋์คํฌ์์๋ถํฐ ์คํฌ๋ฆฝํธ๋ฅผ ์ฝ์ด์์ ์ฆ์ ์คํ์ํจ๋ค. ๊ทธ ์คํฌ๋ฆฝํธ๋ I/O๋ฅผ ์ํํ๊ฑฐ๋, ๋ค๋ฅธ ์ฌ์ด๋ ์ดํํธ๋ฅผ ์คํ์ํฌ ์ ์๋ค. ๊ทธ ํ์module.exports์์ ์ธํ ํ ๊ฐ์ ๋ฐํํ๋ค. -
.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.twoPi = void 0; // @showEmit // @module: commonjs // @noErrors const constants_1 = require("./constants"); exports.twoPi = constants_1.valueOfPi * 2;
-
- ES2015
-
๋ชจ๋ ์ ์๋ export, ๋ชจ๋ ์ฌ์ฉ์ import ๋ฌธ์ ์ฌ์ฉํ๋ค.
-
ESM์ ๋์ ๋ฐฉ์
๋ชจ๋ ๋ก๋๋ ๋น๋๊ธฐ๋ก ๋์ํ๋ค. ์ฒ์์ ํ์ฑ์ ํ๊ฒ๋๋ค. ์คํฌ๋ฆฝํธ๋ฅผ ํ์ฑํ์ฌ import์ export๋ฅผ ํธ์ถํ ๋ถ๋ถ์ ์ฐพ๋๋ค(์ฐพ๊ธฐ๋ง ํ๊ณ ์คํ์ํค์ง๋ ์๋๋ค). ํ์ฑํ ๋, named import์์์ ์คํ๋ฅผ ๊ฐ์งํ๊ณ , exception์ ๋์ง ์ ์๋ค. ์ค์ ์์กด ์ฝ๋๋ ์คํ์ํค์ง ์๊ณ ๋ ์ค๋ฅ๋ฅผ ๊ฐ์งํ ์ ์๋ ๊ฒ์ด๋ค.
ํ์ฑ์ด ๋๋๊ณ ๋๋ฉด, ๋น๋๊ธฐ์ ์ผ๋ก ๋ค์ด๋ก๋๋ฐ๊ณ , importํ ์คํฌ๋ฆฝํธ๋ฅผ ํ์ฑํ๊ฒ ๋๋ค. ๋์ด์ importํ๋ ์คํฌ๋ฆฝํธ๊ฐ ์์ ๋๊น์ง ์์กด ๊ด๊ณ๋ฅผ ๋ํ๋ด๋ "module graph"๋ฅผ ๊ทธ๋ฆฌ๊ฒ ๋๋ค. ์คํฌ๋ฆฝํธ๋ฅผ ์คํํด๋ ๋๋ค๋ฉด, ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ๊ฒ ๋๋ค.
-
.js
// @showEmit // @module: commonjs // @noErrors import { valueOfPi } from "./constants"; export const twoPi = valueOfPi * 2;
-