ETC -

React / ES6 / Webpack 프로덕션 빌드 최적화

  • -

React / ES6 / Webpack 프로덕션 빌드 최적화

안녕하세요 TriplexLab 입니다.

오늘은 요즘 프론트앤드 개발에 필수인 ES6, Webpack, React 의 환경 설정에 대해서 알아보도록 하겠습니다.

많은 분들이 저에게 React, Webpack 빌드 최적화에 대해서 많이들 물어보셔서 이번 기회에 정리합니다.

package.json 파일은 현재 프로젝트에서 사용하는 라이브러리(의존성 모듈)의 버전들을 관리하는 파일입니다.

한번 설정해놓으면 다른 프로젝트 할때마다 기존 package.json 파일들을 참고 하는것 같습니다.

왜냐하면 버전이 달라서 빌드할때 에러가 날 경우가 있습니다. 그럴때 참고하는것이 좋은것 같습니다.

//package.json

{
  "name": "React",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "prod": "webpack --mode=production",
    "dev": "webpack --mode=development",
    "watch": "webpack-dev-server --mode development --open --hot"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1",
    "@babel/preset-react": "^7.12.5",
    "babel-loader": "^8.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^6.3.0",
    "css-loader": "^3.4.1",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^4.5.0",
    "node-sass": "^5.0.0",
    "postcss-loader": "^4.0.4",
    "sass-loader": "^10.0.5",
    "style-loader": "^1.1.2",
    "url-loader": "^4.1.1",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.11.0",
    "webpack-merge": "^5.0.9"
  },
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
  }
}

 

여기서는 각각의 의존성에 대해서 자세하게는 이야기 하지 않을것 입니다.

혹시 각 의존성에 대해서 자세한 설명을 보고 싶은분들은 다음 사이트를 참고해주세요.

https://thdbsgh3443.gitbook.io/webpack/webpack-core-package

 

webpack의 핵심 패키지

 

thdbsgh3443.gitbook.io

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const { merge } = require('webpack-merge');
require('@babel/polyfill');

module.exports = {
    resolve: {
        extensions: ['.js', '.css', '.scss'],
        alias: {
            '@' : path.resolve(__dirname, 'src'),
        },
    },
    entry: {
        app: [
            '@babel/polyfill',
            path.join(__dirname, './src/index.js')
        ]
    },
    module: {
        rules: [
            { //react 프로젝트할때 추가합니다. ST
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)|(dist)/,   //node_modules디렉토리 아래있는 파일들은 제외하고, | dist디렉토리 제외하고
                use: {
                    loader: 'babel-loader'
                }
            },
            { //react 프로젝트할때 추가합니다. ED
                test: /\.s[ac]ss$/i,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback:'style-loader',
                    use: [
                        'css-loader',
                        'postcss-loader',
                        'sass-loader'
                    ]
                })
            },
            { // font loader
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    {
                      loader: 'file-loader',
                      options: {
                          name: '[path][name].[ext]',
                      }
                    }
                ]
            },
            { // images css에서 background-image 속성 loader
                test: /\.(png|svg|jpe?g|gif)$/,
                loader:'url-loader',
                options: {
                  outputPath: 'images/',
                  name: "[name].[ext]", //outputPath로 나오는 파일명을 동일한 파일명으로 지정하겠다.
                  limit: 1000
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, './public/index.html'),
            filename: 'index.html'
        }),
        new CopyPlugin({
            patterns: [ 
                { from: 'src/assets', to: '' }
            ]
        }),
        new ExtractTextPlugin({
            filename: 'styles.css',
            disable: false,
            allChunks: true
        }),
        new CleanWebpackPlugin()
    ],
    output: {
        filename: '[name].js',
        path: path.join(__dirname, 'dist')
    },
}

 

// .babelrc
{
    "presets": [
        "@babel/env",
        "@babel/react"
    ]
}

위에 코드를 본인 프로젝트 폴더에 하나씩 파일을 만들어서 복붙하여 만들어 주세요.

그리고 npm install를 하므로써 모든 라이브러리(의존성 모듈)을 설치 합니다.

// 터미널
npm install

다음과 같은 폴더 구조를 만들었습니다.

// 터미널

npm run prod  //실제 서버에 배포용도
npm run dev  //테스트 서버에 배포용도
npm run watch //로컬에서 테스트할 용도
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.