Skip to content

Npm:Module

Npm에서 모듈 만드는 방법 등 설명

Frontend TypeScript Library Module Setup

npm 대신 yarn

npm install -g yarn

그리고 npm 프로젝트 초기화:

mkdir demo-project
cd demo-project
yarn init -y

Webpack 번들러 설치

yarn add -D webpack webpack-cli

webpack 기본 설정 방법을 참조하거나, webpack-cli로 설정파일을 생성한다:

yarn run webpack-cli init

간단한 질의 결과는:

$ yarn run webpack-cli init
[webpack-cli] For using this command you need to install: '@webpack-cli/generators' package.
[webpack-cli] Would you like to install '@webpack-cli/generators' package? (That will run 'yarn add -D @webpack-cli/generators') (Y/n) y
? Which of the following JS solutions do you want to use? Typescript
? Do you want to use webpack-dev-server? Yes
? Do you want to simplify the creation of HTML files for your bundle? No
? Do you want to add PWA support? No
? Which of the following CSS solutions do you want to use? none
? Do you like to install prettier to format generated configuration? Yes
? Pick a package manager: yarn
? Overwrite package.json? overwrite

완료 후 사용하지 않는 종속성은 제거한다.

yarn remove @webpack-cli/generators

종속성 업데이트 후 정상적으로 빌드 되는지 확인해 보자.

yarn
yarn build:dev
cat dist/main.js  ## check result

TypeScript 설치

직전 스탭에서 이미 typescript는 설치되었을 것이다. 만약 없다면 yarn add -D typescript 명령으로 설치하자.

INFORMATION

ts-loader 대신 babel과 함께 @babel/preset-typescript을 설치할거다.

직전 스탭에서 tsconfig.json은 이미 생성되어 있을 것이다. 만약 없다면 yarn run tsc --init명령으로 직접 생성해야 한다. 스팩은 ES2021+(그냥 최신: esnext)을 사용한다. 1 상세 설정은 생성된 파일을 편집한다.

현재 사용하고 있는 tsconfig.json는 다음과 같다:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "allowJs": true,
    "paths": {
      "*.ts": ["*"],
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"],
  "exclude": ["node_modules", "dist"]
}

Babel 트랜스컴파일러 설치

yarn remove ts-loader
yarn add -D @babel/core @babel/preset-env @babel/preset-typescript babel-loader

webpack의 rules에 babel-loader 추가: 2

module: {
  rules: [
      {
        test: /\.(js|ts|tsx)$/i,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-typescript',
            ],
          },
        },
      },
  ]
}

INFORMATION

babel.config.json는 만들지 않는다. webpack.config.js의 options에 넣는다.

prettier 스타일 체커 설치

yarn add --dev prettier

package.json에 스타일 설정 추가:

  "prettier": {
    "printWidth": 88,
    "tabWidth": 2,
    "useTabs": false,
    "semi": true,
    "singleQuote": true,
    "quoteProps": "as-needed",
    "trailingComma": "all",
    "bracketSpacing": false,
    "bracketSameLine": false,
    "arrowParens": "avoid",
    "htmlWhitespaceSensitivity": "ignore",
    "vueIndentScriptAndStyle": false,
    "endOfLine": "lf"
  }

ESLint 린터 추가

INFORMATION

참고로 TSLint는 deprecated 되었다.

yarn add -D eslint eslint-webpack-plugin @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-prettier

eslint 설정을 추가한다. 쉽게 만드는 방법은:

yarn create @eslint/config

질문 결과:

✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · prompt
✔ What format do you want your config file to be in? · JSON
✔ What style of indentation do you use? · 4
✔ What quotes do you use for strings? · single
✔ What line endings do you use? · unix
✔ Do you require semicolons? · Yes
The config that you've selected requires the following dependencies:

@typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
✔ Would you like to install them now with npm? · No
Successfully created .eslintrc.json file in /home/your/Project/answer-dev/api
Done in 32.93s.

.eslintrc.json파일이 만들어지면 package.json의 eslintConfig 속성에 추가한다.

  "eslintConfig": {
    "root": true,
    "env": {
      "browser": true,
      "es2021": true,
      "node": true
    },
    "extends": [
      "eslint:recommended",
      "plugin:@typescript-eslint/recommended",
      "plugin:prettier/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "ecmaVersion": "latest",
      "sourceType": "module"
    },
    "plugins": [
      "@typescript-eslint",
      "prettier"
    ],
    "rules": {
      "prettier/prettier": "error",
      "indent": [
        "error",
        2
      ],
      "linebreak-style": [
        "error",
        "unix"
      ],
      "quotes": [
        "error",
        "single"
      ],
      "semi": [
        "error",
        "always"
      ]
    },
    "ignorePatterns": [
      "node_modules",
      "dist"
    ]
  },

prettier와 중복되는 rule 이 있더라도 가급적 eslint의 rule 을 사용하자. prettier/prettier rule은 어떤 에러인지 구체적으로 출력되지 않는다.

코드 최소화(Minification)

Webpack v4+의 production mode에서는 기본으로 코드를 최소화(Minification)한다.

다른 옵션을 사용하고 싶다면 공식 문서를 참조.

Jest 유닛 테스트

yarn add -D jest babel-jest ts-jest @types/jest

package.json에 jest 속성으로 ts-jest를 위한 설정을 추가한다:

  "jest": {
    "preset": "ts-jest",
    "moduleNameMapper": {
      "@/(.*)$": "<rootDir>/src/$1"
    }
  }

(필요하다면) SCSS

yarn add -D sass node-sass sass-loader

(필요하다면) cypress e2e Test

yarn add -D cypress

(필요하다면) 코드 난독화(Obfuscate)

uglifyjs와 uglifyjs-webpack-plugin 사용을 고려하면 된다.

See also

Favorite site

References