HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
webpack

webpack

1. init 후 webpack 설치

  • 프로젝트 init
    • npm init -y
  • 웹팩설치
    • npm i -D webpack webpack-cli
  • webpack.config.js 설정
    • entry : ‘Webpack’이 파일을 처음 읽어들이기 시작하는 진입점
    • output: entry에서 설정한 의존성 트리의 결과물(번들)을 반환하는 설정
      • output.path : 결과물이 저장될 경로
      • output.filename : 결과물의 파일 이름 지정
        • 자동으로 dist 붙여서 생성'./dist/app.bundle.js'→ ‘./app.bundle.js’
      module.exports = { entry: './src/app.js', output: { filename: './dist/app.bundle.js' } };
  • index.html 작성
    • dist/index.html의 script 경로를 지정
    • <!-- dist/index.html --> ... <body> <script src="app.bundle.js"></script> //HTML Webpack Plugin적용 후 삭제 </body> ...
  • scripts 내용 수정
    • -d flag 있을 때 error 확인
      • "webpack -d --watch" → “webpack —-watch”
      // package.json "scripts": { "dev": "webpack --watch", // 개발용 (development) "prod": "webpack -p" // 제품용 (production) }

2. HTML Webpack Plugin 적용

html-webpack-plugin은 budle폴더(dist)에 html파일을 배포를 위한 처리작업 이후 삽입해주는 플러그인 ejs, 공백제거, hash화 등 기능사용 가능
  • webpack-plugin 설치
    • $ npm i html-webpack-plugin -D
    • // webpack.config.js const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { ... output: { path: __dirname + '/dist', filename: 'app.bundle.js' }, plugins: [ new HtmlWebpackPlugin({ template: "./index.html", }), ], };

3. style-loader와 css-loader 적용

loader란 파일을 가져 오거나 ‘Load’할 때 파일을 사전 처리를 도와주는 기능. Typescript→Javascript, 인라인이미지→데이터URL , js모듈에서 css파일의 import 등의 역할 가능
  • 개념 정리
    • css-loader: css파일을 js에서 모듈처럼 사용할 수 있도록 변환
      style-loader: css-loader로 js화된 스타일을 돔(DOM)에 적용할 수 있도록 함
    • module의 속성 소개
      • test : 정규표현식 형태로 적용되는 파일들을 설정함
        • (/\.css$/ : css로 끝나는 모든 파일)
      • use : 지정된 ‘loader’가 test 에서 적용한 파일들을 컴파일함
  • 설치
    • $ npm i style-loader css-loader -D
    • 추가
      • // webpack.config.js module.exports = { ... module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], }, ], }, ... };
    • test
      • app.css 파일 생성 후, app.js에서 import 한 후 test (css적용확인)
        • notion image

4. sass-loader 적용

  • 설치
    • $ npm i sass-loader node-sass -D
    • 설정 변경
      • // webpack.config.js module.exports = { ... module: { rules: [ { test: /\.scss$/, use: ['style-loader','css-loader','sass-loader'] }, ], }, ... };
    • 작동확인
      • app.scss 파일생성 후, scss 중첩문법 적용 후, app.js에서 import
        • notion image