donaricano-btn

React-testing-library 란?

리엑트를 개발하다보면 TDD에 관해서 한번씩 생각하게 합니다. 화면에 소스가 렌더링 되기전에 커맨드라인으로 미리 확인 할 수 있다면 개발속도가 더 빠를까라는 생각을 하게 됩니다. 그러나 개발의 생산성을 올리기위해 TDD를 진행한다면 이 방법은 해답이 될 수도 있고 아닐 수도 있습니다.

TDD는 오히려 빠른개발을 방해할 수도 있습니다. 하지만 더 견고한 어플리케이션을 제작할 수 있다는 사실은 반론할 수 없습니다. 더 견고하고 신뢰할 수 있는 웹 서비스를 만들기 위해서 react-testing-library를 사용합니다.

react-testing-library는 결국 react 컴포넌트의 DOM테스트를 하기위한 TDD 도구로 사용됩니다. Testing-library란 패키지안에 react-testing-libary가 존재하며 설치방법 또한 npm 을 이용하여 간편하게 설치가 가능합니다.

npm install --save-dev @testing-library/react

react 테스팅 도구로 과거에는 enzyme을 사용했지만 react 의 공식문서에서 react-testing-library 를 테스트 도구로 사용하는것을 권장하고 있습니다. 지금부터 react-testing-library의 사용법을 천천히 따라가 보도록 하겠습니다.

https://testing-library.com/docs/react-testing-library/intro

 

Testing Library · Simple and complete testing utilities that encourage good testing practices

Simple and complete testing utilities that encourage good testing practices

testing-library.com

 
블로그 이미지

리딩리드

,
donaricano-btn

웹팩 멀티 번들관리

(https://webpack.js.org/guides/output-management/ - 번역)


1. 멀티 번들처리

- 프로젝트 규모가 증가 할 수록 많은 수에 번들파일이 생성된다. 웹팩은 이런 번들 파일을 index.html 에서 관리하는 방법을 제공한다.


2. 멀티 번들 설정

1) project

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- /dist
  |- /src
    |- index.js
+   |- print.js
  |- /node_modules

2) print.js

export default function printMe() {
  console.log('I get called from print.js!');
}

3) index.js

  import _ from 'lodash';
+ import printMe from './print.js';

  function component() {
    var element = document.createElement('div');
+   var btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

+   btn.innerHTML = 'Click me and check the console!';
+   btn.onclick = printMe;
+
+   element.appendChild(btn);

    return element;
  }

  document.body.appendChild(component());

4) index.html 

  <!doctype html>
  <html>
    <head>
-     <title>Asset Management</title>
+     <title>Output Management</title>
+     <script src="./print.bundle.js"></script>
    </head>
    <body>
-     <script src="./bundle.js"></script>
+     <script src="./app.bundle.js"></script>
    </body>
  </html>

- 엔트리 포인트에 따라 번들해야될 js 가 생성된다. 그리고 이 파일들을 임포트한다.

5) webpack.config.js

  const path = require('path');

  module.exports = {
-   entry: './src/index.js',
+   entry: {
+     app: './src/index.js',
+     print: './src/print.js'
+   },
    output: {
-     filename: 'bundle.js',
+     filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

- 엔트리 포인트를 설정하여 각각의 번들을 생성하고 관리할 수 있다.

- 문제점: 만약 엔트리 포인트이름을 변경하거나 새로운 엔트리가 생기게 된다면 어떻게 될까?? index.html 파일에는 기존에 있던 파일을 그대로 참조하고 있다. 일일이 수정해야되는 번거로움이 있다.


HtmlWebpackPlugin


1. HtmlWebpackPlugin 이란?

- 위의 문제점보완 하고자 webpack에서 제공하는 플러그인이다. 

- 해당 플러그인을 설치하면 변하는 엔트리포인트에 대하여 개발자가 index.html의 js 파일 참조를 수정할 필요 없다


2. 설치

npm install --save-dev html-webpack-plugin


3. webpack.config.js

  const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management'
+     })
+   ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    } 



CleanWebpackPlugin

1. CleanWebpackPlugin

- 프로젝트를 진행하다보면 dist의 사용하지 않는 파일들이 존재한다. 이런 파일들을 자동으로 정리(제거)해준다.


2. 설치

npm install clean-webpack-plugin --save-dev


3. webpack.config.js

 const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };


블로그 이미지

리딩리드

,
donaricano-btn

웹팩의 로더사용(webpack Loader)

(https://webpack.js.org/guides/asset-management/ - 번역)


1. 로더란?

- 프론트엔드 개발을 하면서 필요한 자원들(images, css, font, json....)을 관리하기 위해 필요하다

- 웹팩에서는 모든 파일을 모듈 단위로 다룬다. 그리고 이런 모듈을 동적으로 묶음으로서 파일간의 의존관리를 하고 필요없는 파일은 제외시킬 수 있다.


2. Loading CSS

1) 설치

npm install --save-dev style-loader css-loader

2) webpack.config.js

 const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
+   module: {
+     rules: [
+       {
+         test: /\.css$/,
+         use: [
+           'style-loader',
+           'css-loader'
+         ]
+       }
+     ]
+   }
  };

- 원하는 파일에 css 파일을 import 시키면 사용 가능하다.

- webpack 내부적으로 모듈화 시킬 때 <head> 에 자동으로 인젝션한다.

3) style.css

.hello {
  color: red;
}

4) index.js

  import _ from 'lodash';
+ import './style.css';

  function component() {
    var element = document.createElement('div');

    // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
+   element.classList.add('hello');

    return element;
  }

  document.body.appendChild(component());

5) npm run build


3. 기타로더

- image, font, json, xml..... 사이트에서 확인가능하다.



'Tools > webpack' 카테고리의 다른 글

[webpack] 웹팩 멀티 번들관리  (0) 2018.06.21
[webpack] 웹팩 기본 사용법 - webpack HelloWorld  (0) 2018.05.15
블로그 이미지

리딩리드

,
donaricano-btn

웹팩 기본 사용법 - webpack HelloWorld

(https://webpack.js.org/guides/getting-started/ 번역)


1. 웹팩 로컬 설치

- 웹팩을 설치하기 이전에 node.js를 설치해야한다.

mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev


2. 프로젝트 구조설정

1) 프로젝트 구조

  webpack-demo
  |- package.json
+ |- index.html
+ |- /src
+   |- index.js

2) src/index.js

- 해당 프로젝트에서 lodash 라이브러리를 사용했다.

function component() {
  var element = document.createElement('div');

  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

3) index.html

- lodash 라이브러리를 html문서에 직접 참조했다.

- webpack을 이용하여 차후에 script 소스들을 관리한다.

<!doctype html>
<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>

4) package.json

  {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
+   "private": true,
-   "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9"
    },
    "dependencies": {}
  }

- private 을 true로 설정하고 엔트리 포인트인 main 을 제거하였다. 이유는 해당 소스가 배포될때 발생할 수 있는 사고를 미연에 방지 할 수 있다.


3. 번들 만들기

- webpack에서 모든 단위는 모듈에서 시작한다. js, image, css etc...모든 것은 모듈이 된다. 그리고 이런 모듈을 모아서 컴파일 단계를 거치면 하나의 묶음인 번들(bundle)이 생성되는 것이다. 

- 번들을 사용 함으로서 서버의 request를 줄이고 모듈들의 의존관리를 쉽게 할 수 있다

1) 프로젝트 구조 변경과 lodash 의존성 포함

- 앞의 예제에서 lodash를 html문서에 삽입하였지만 웹팩을 이용하여 의존성 관리가 되도록 추가한다

- --save로 설치한다면 package.json 설정에서 product 레벨에서 사용가능하게 된다. (--save-dev 는 개발환경시 필요)

npm install --save lodash

- dist 폴더를 추가하여 번들링된 파일을 담을 수 있도록 변경한다

 webpack-demo
  |- package.json
+ |- /dist
+   |- index.html
- |- index.html
  |- /src
    |- index.js

2) 소스 수정

- lodash를 의존관리가 가능하도록 추가 했으니 소스도 변경해야 한다.

- src/index.js

+ import _ from 'lodash';
+
  function component() {
    var element = document.createElement('div');

-   // Lodash, currently included via a script, is required for this line to work
+   // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
  }

  document.body.appendChild(component());

- dist/index.html

  <!doctype html>
  <html>
   <head>
     <title>Getting Started</title>
-    <script src="https://unpkg.com/lodash@4.16.6"></script>
   </head>
   <body>
-    <script src="./src/index.js"></script>
+    <script src="bundle.js"></script>
   </body>
  </html>

- 기존에 추가했던 js 파일을 제거하고 bundle.js 라는 최종 번들 파일만을 참조하고 있다.

(현재는 webpack.config.js 를 설정하지 않아서 run 할 시 main.js 가 생성 될 것이다)

3) 화면 확인

npx webpack

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 3003ms
Built at: 2018-2-26 22:42:11
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

- npx webpack 

- npx는 node 버전 8.2 이상부터 가능하다

- 이후에 dist에 있는 html 파일을 클릭하면 해당 문구가 출력된다.(단 bundle.js 가 없으므로 main.js를 참조해야한다)


4. 설정파일 작성 - webpack.config.js

- 웹팩은 프로젝트마다 설정을 다르게 할 수 있도록 설정파일을 제공한다.

1) project

  webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js

2) webpack.config.js

- output의 파일명이 bundle.js 로 되었다. 위에서 main.js가 생성되었다면 설정파일 이후로 bundle.js가 생성된다.

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

3. run

npx webpack --config webpack.config.js

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 328ms
Built at: 2018-2-26 22:47:43
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

- npx webpack --config webpack.config.js


5. npm script

- npx 커맨드를 간단하게 줄이기 위하여 NPM 커맨드를 설정한다

1) package.json

 {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9",
      "lodash": "^4.17.5"
    }
  }

- npm run build 명령어를 npx 대신 사용 할 수 있다

npm run build

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 323ms
Built at: 2018-2-26 22:50:25
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.


'Tools > webpack' 카테고리의 다른 글

[webpack] 웹팩 멀티 번들관리  (0) 2018.06.21
[webpack] 웹팩의 로더사용(webpack Loader)  (0) 2018.06.20
블로그 이미지

리딩리드

,