Home React Webpack 설정
Post
Cancel

React Webpack 설정

package.json


1
npm init

git


1
git init
  • .gitignore
    • 루트에 .gitignore 파일을 생성 후 아래와 같이 git에 저장하고 싶지 않은 폴더 및 파일을 입력한다.
1
2
3
node_modules
dist/*
.DS_Store

react


1
yarn add react react-dom

babel


1
yarn add @babel/runtime
1
yarn add --dev @babel/core babel-loader @babel/preset-react @babel/preset-env @babel/plugin-transform-runtime

webpack


1
 yarn add --dev webpack webpack-dev-server webpack-cli html-webpack-plugin copy-webpack-plugin

  • webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  mode: "development",
  entry: "./index.js", // 모듈이 시작되는 부분 (엔트리 포인트)
  output: {
    path: path.resolve("./dist"), // 모듈이 시작되는 부분부터 모두 합쳐준 결과물을 저장하는 곳
    filename: "bundle.js",  // 합쳐진 결과물 파일 이름
  },
  resolve: {
    extensions: [".jsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.(js)x?$/,  // js, jsx로 끝나는 모든 파일
        exclude: /node_module/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.css$/,  // css로 끝나는 모든 파일
        use: ["style-loader", "css-loader"], // css-loader는 css파일을 모듈 처럼 사용할 수 있게 해주는 로더이고  style-loader는 css-loader가 처리해준 모듈처럼 사용할 수있게 한 js파일의 css문자열을 브라우저에 html에 주입시켜 브라우저에 보여질 수 있도록 처리해주는 로더이다
      },
      {
        test: /\.s[ac]ss$/,
        use: ["style-loader", "css-loader", "sass-loader"], // 로더는 한 파일에 여러개가 실행될 때 뒤에서 부터 앞으로 실행된다.
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
        exclude: /node_modules/,
        use: ["file-loader?name=[name].[ext]"],  // 이미지 파일을 모듈로 사용할 수 있도록 변환하는 역할을 하는 로더이다.
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
    new CopyPlugin({
      patterns: [{ from: "./src/assets", to: "" }],
    }),
  ],
};

  • babel.config.js
1
2
3
4
5
module.exports = {
  presets: ["@babel/env", "@babel/react"],
  plugins: ["@babel/plugin-transform-runtime"],
};

  • package.json
    • yarn start
      • 개발환경
    • yarn build
      • 하나로 만들어진 자바스크립트 파일이 dist 폴더에 bundle.js라는 파일 이름으로 생성된다.
1
2
3
4
5
6
7
8
{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development --config ./webpack.config.js",
    "build": "webpack --mode production --config ./webpack.config.js"
  },
}

This post is licensed under CC BY 4.0 by the author.