본문 바로가기
개발팁

Webpack 사용방법

by 몸에배인매너 2022. 3. 27.

1. PowerShell 을 최신버전으로 준비 > PowerShell과 VScode 둘다 관리자권한으로 실행

2. Setting > terminal > 새로 설치한 PowerShell

3. PowerShell 실행정책 변경 후 재부팅 https://docs.microsoft.com/ko-kr/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.2 

 

실행 정책 정보 - PowerShell

PowerShell 실행 정책을 설명하고 이를 관리하는 방법을 설명합니다.

docs.microsoft.com

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser   # 모든 스크립트 허용
Get-ExecutionPolicy -List   # 실행정책 바뀐거 확인

 

5. Scoop 설치 https://scoop.sh/

 

Scoop

Scoop, a command-line installer for Windows

scoop.sh

iwr -useb get.scoop.sh | iex

 

6. Node.js 설치 (scoop 안에 깔린다)

scoop install nodejs

 

 

7. 지금 열려있는 프로젝트 기반으로 package.json 을 구성한다.

npm init -y

 

8. package.json 파일안에 webpack을 사용한다고 써넣고, webpack-cil 을 설치해준다.

"main": "index.js",  // 중심이 되는 js파일을 기입
"scripts": {
    "build": "webpack",
    "dev": "webpack serve"
  },

 

npm i -D webpack webpack-cil

 

9. 최상단에 webpack.config.js 파일 생성 (어떻게 처리할껀지 설정)

const path = require('path')        // 경로 가져오기
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
// quick cooking this website html. ps) but this is just html not a django.html
// const HtmlWebpackPlugin = require('html-webpack-plugin')
// analyzing config this website.
const bundleAnalyzerPlugin = require('webpack-bundle-analyzer').bundleAnalyzerPlugin
/*
    mode   : export mode.
    entry  : convert file path.
    output : converted file path.
    devtool: converted javascript attributes are here.
    module : what you want to export files and rules.
*/
module.exports = {        // 이걸 왜 만드는지 설명
    // 1) 베이킹 타겟 및 베이킹 모드.
    // mode list production , development ,none
    mode   : 'production',
    entry  : {        // 어떤 파일을 읽어오는지
        bundle : path.resolve(__dirname, 'src/js/bundle.js'),
    },
    // 2) 출력 셋업.
    output : {        // 파일을 출력하는 위치
        path : path.resolve(__dirname, 'static/js'), // convert 완료 후 저장소.
        filename : '[name].js',        // convert 완료 후 저장될 이름.
        clean : true,                                // run build 시 contenthash는 완료 파일 이외 모두 삭제하고 가장 최근거만.
        // assetModuleFilename : '[name].[ext]',     // convert 이미지의 이름과 확장자를 뽑아서 static/js 공간에 저장해준다. ps) 근데 이 기능은 좀 별로인거같다.
    },
    // 3) 자바스크립트 source map도 같이 출력.
    devtool : 'source-map',
    // devServer : {     // 서버 없이 html로만 작업할 때 자동으로 js을 추가해줌
    //     static : {
    //         directory : path.resolve(__dirname, 'static/js'),
    //     },
    //     port : 3000,
    //     open : true,
    //     hot : true,
    //     compress : true,
    //     historyApiFallback : true,
    // },
    module : {
        // use for scss set-up.
        rules : [
            {
                // scss 를 js에 병합.
                test : /\.scss$/,     // 받아올 확장자
                use : ['style-loader','css-loader','sass-loader'],
            },
            {
                // 자바스크립트 합치지만 node_modules는 제외한다.
                test : /\.js$/,     // 받아올 확장자
                exclude : /node_modules/,
                use : {
                    loader : 'babel-loader',
                    options : {
                        presets : ['@babel/preset-env'],
                    },
                },
            },
            // // 모든 이미지 확장자들을 받아서 저장한다.
            // {
            //     test : /\.(png|svg|jpg|jpeg|gif|ico)$/i,
            //     type : 'asset/resource'
            // },
        ]
    },
    plugins : [
        // create webpack basic html.   // 서버 없이 html로만 작업할 때 자동으로 js을 추가해줌
    //     new HtmlWebpackPlugin({
    //         title : 'Discord merlin-Bot',
    //         filename : 'main.html',
    //         template : 'templates/main.html',
    //     })
        // 웹사이트 분석할때만 쓸것.
           new BundleAnalyzerPlugin(),
    ]
}

 

10. 합쳐줄 파일을 최상단에서 해당 경로를 만들어 삽입

src/js            # js파일
src/styles       # scss파일

 

11. 파일을 읽어오기 위해 필요한 플러그인 설치

npm i -D sass style-loader css-loader sass-loader      # style파일 읽음
npm i -D html-webpack-plugin
npm i -D webpack-dev-server
npm i -D babel-loader @babel/core @babel/preset-env    # js파일을 불러옴
npm i -D webpack-bundle-analyzer                       # 웹사이트에 대한 분석

 

12. 실행

npm run build

 

13. static 폴더의 메인 js 로 합쳐졌기 때문에 이 js 파일 하나만 불러오면 된다.

 

[각주:1]

  1. 괴짜코딩, https://github.com/github01main/powershell_dummies [본문으로]

'개발팁' 카테고리의 다른 글

MySQL 사용방법 & pymysql (feat.Python)  (0) 2022.04.06
구글 이메일 API  (1) 2022.03.29
pipenv 가상환경  (0) 2022.03.07
Visual Studio Code 세팅  (0) 2022.03.07
Override, Method (메소드) 란  (0) 2022.02.16

댓글