React webpack사용하기 (Babel, webpack-dev-server)

Joey Hong·2020년 6월 22일
0

React/Next.js

목록 보기
1/3

webpack.config.js
client.jsx
WordRelay.jsx
index.html

웹팩

웹팩이란?

  • html에서는 script 태그를 이용해 하나의 JavaScript 파일만 불러올 수 있다.
  • 하지만 하나의 JavaScript 파일에 모든 component들을 넣는다면 코드의 길이가 너무 길어져
    이해하기도 힘들고 수정도 불필요하게 힘들어진다.
  • 여러 JavaScript 파일들은 하나의 파일로 합쳐주는 역할을 하는 것이 바로 wepback이다.
  • 도중에 코드를 수정할 수도 있으며 Babel/text를 적용할 수 있다.
  • Node.js를 알아야 사용하기 편리하다는 점은 있다.

웹팩 설치

npm init 원하는 디렉토리에 해당 커맨드를 치면 "package.json" 파일이 생성된다.

  • "npm init" 이후 "npm"으로 설치를 하면 "package-lock.json"파일과 "node_modules" 라이브러리가 생기며 그 안에 설치내용이 저장된다.
  • 라이브러리에 저장되는 설치파일의 목록은 "package.json"에 저장된다

npm i react react-dom 리액트와 리액트돔을 설치해준다
npm i -D webpack webpack-cli "-D"는 서비스를 위한게 아닌 개발용 프로그램이란 의미다.

  • "package.json"을 확인해보면 "devDependencies" 목록에 웹팩이 설치된 것을 볼 수 있다.

웹팩으로 프로그램 실행시키기

  • 웹팩을 실행시키기 위한 방법 중 두가지를 소개한다.
    1. npm run dev
    2. npx webpack
  • 작업중인 디렉토리에서 아래 명령어 중 하나를 치고 웹에서 "localhost"로 들어가면 된다

웹팩 dev-server와 hot-loader

  • 코드가 변경될 때마다 매번 프로그램을 재실행시켜야하는 번거로움이 있다.
  • 이를 해결하기 위해 webpack-dev-server와 webpack hot-loader를 설치해준다.
  • 하지만 "webpack.config.js" 파일이 변경된 경우는 수동으로 재실행해줘야 한다.

npm i -D react-hot-loader 수정사항을 감지한다
npm i -D webpack-dev-server 수정사항이 발견됐을 때 자동으로 프로그램을 재실행해준다
`"webpack.config.js" 파일이 변경된 경우는 수동으로 재실행해줘야 한다.

  1. npm run dev은 "http://localhost:8080"이라는 서버 주소에 프로그램을 실행시킨다
    • "package.json" 파일의 scripts 항목을 아래와 같이 수정해준다.
    "scripts: {
        "dev": "webpack-dev-server --hot"
    }
  1. npx webpack은 그대로 "localhost" 주소를 이용하면 된다

바벨 설치

  • 웹팩은 jsx파일을 읽을 수 없기에 Babel을 설치해줘야한다.
    npm i -D @babel/core 기본 바벨

  • 필요한 기능에 맞게 바벨의 모듈들을 설치해준다.
    npm i -D @babel/preset-env 최신 JavaScript를 사용가능하게 해준다
    npm i -D @babel/preset-react jsx를 사용가능하게 해준다
    npm i -D babel-loader 바벨과 웹팩을 연결해준다
    npm i -D @babel/plugin-proposal-class-properties state를 사용가능하게 해준다 (setState)

파일 설정하기

  • "webpack.config.js", "client.jsx", "WordRelay.jsx", "index.html" 파일 네가지를 생성해 내용을 아래와 같이 바꿔준다.
  • "WordRelay.jsx"는 만들고있는 프로그램 이름으며 원하는 명으로 변경 가능하다.
  • 여기서 jsx확장자는 js로 변경 가능하지만 jsx문법을 사용하고있다면 리액트 파일임을 바로 알 수 있도록 jsx확장자를 사용하는 것이 편리하다.

webpack.config.js

const path = require('path'); // Import Node.js' path controller

module.exports = {
    name: 'word-relay-setting', // Any name. Unnecessary option
    mode: 'development', // For real service:production
    devtool: 'eval', // Fast. "hidden-source-map" for real service
    resolve: {
        extensions: ['.js', '.jsx'] // No need to write .js or .jsx for files under entry
    },

    // Important part
    entry: {
        app: ['./client'], // Files to make the output file. If files are imported in another file, they don't need to be written down here. 'WordRelay.jsx' is imported in 'client.jsx'
    },
    
    module: { //These modules are applied to the entries to produce outputs
        rules: [{
            test: /\.jsx?$/, //Regular expression. Apply rules to js and jsx file
            loader: 'babel-loader', // specifies which rule to apply
            options: { // Options of the module (i.e. babel)
                presets: [
                	['@babel/preset-env', {
                    targets: {
                    	browsers: ['> 5% in KR', 'last 2 chrome versions'],
                    },
                    debug: true,
                	}],
                '@babel/preset-react',
                ],
                plugins: [
                	'@babel/plugin-proposal-class-properties',
                    'react-hot-loader/babel',
                ],
            },
        }],
    },

plugins: [ // extra extensions
	new.webpack.LoaderOptionsPlugin({ debug: true }), // applies "debug: true" to all the options of the loader
],

    output: {
        path: path.join(__dirname, 'dist'), // Set's the path to <current directory>/dist
        filename: 'app.js'  //output file
    },
};

client.jsx

const React = require('react');
const ReactDom = require('react-dom');

const { hot } = require('react-hot-loader/root');

const WordRelay = require('./WordRelay');

const Hot = hot(WordRelay);

ReactDom.render(<Hot />, document.querySelector('#root'));

WordRelay.jsx

const React = require('react');
const { useState, useRef } = React;

const WordRelay = () => {
}

module.exports = WordRelay;

index.html

<html>
    <head>
        <meta charset="UTF-8" />
        <title>끝말잇기</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="./app.js"></script> // bring app.js
    </body>
</html>

웹팩 재설치

npm i "package.json"에 있는 것들을 전부 설치해준다

  • "webpack.config.json", "client.jsx", "package.json", "package-lock.json" 파일만 있다면 npm i로 위의 모든 설치와 설정들을 완료할 수 있다.
profile
개발기록

0개의 댓글