728x90
 

🌲webpack


install


webpack과 cli(커맨드 라인 인터페이스 지원) 그리고 cli버전과 맞추기 위해 @next로 설치

*webpack-dev-server는 webpack-cli가 선행되어야 자동가능하다.

npm i webpack webpack-cli webpack-dev-server@next

 

scripts

package.json


webpack 개발모드(--mode development)와 제품 모드(--mode production) 설정

  "scripts": {
   "dev": "webpack-dev-server --mode development",
   "build": "webpack --mode production"
  },

 

config

webpack.config.js


parcel-bundler는 기본옵션이 제공되나 webpack은 직접 구성 옵션을 설정해줘야 한다. 규모있는 프로젝트에서 세세한 설정을 지정해 활용하기 좋다. webpack.config.js는 브라우저 환경이 아닌 node.js환경에서 작동한다. 

parcel에서의 import,export와 비슷한 개념으로 이해하면 쉬운데 entry는 경로를 불러들이는 진입점, ouput은 이 결과물을 반환하는 절대경로에 관련된 설정을 말한다.

추가로 플러그인을 설치한 후 이 파일에서 상세 옵션을 지정해준다. (지금부터 나올 플러그인들 모두 이 파일을 거쳐간다.)

 

const path = require('path')

module.exports = {
  entry: './js/main.js',
  output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  }
}

-> ./js/main.js에서 불러들인 내용을 번들하여 dist폴더에 main.js라는 이름으로 결과물을 반환

 

entry ./js/main.js 경로를 불러들이는 진입점
output.path const path = require('path')
path.resolve(__dirname, 'dist')
결과물(번들)을 반환하는 절대경로
output.filename main.js 결과물 파일명
output.clean true 기존에 생성된 디렉토리 제거, clean옵션을 사용하지 않으면 디렉토리명과 파일명을 새로 지정할 때마다 새로이 생성된다.

*output.path와 outputfilename을 설정해주지 않아도 기본적으로 dist디렉토리에 entry파일명 그대로 생성된다.

*dirname은 해당하는 파일의 실제 경로를 나타내는 nodejs의 전역 변수

 

 

🌍 plugin

번들링 후 결과물의 처리 방식 등 다양한 플러그인들을 설정


html-webpack-plugin

html파일을 템플릿으로 생성할 수 있게 도와주는 플러그인이다. html파일에 link,script로 css,js을 연결하지 않아도 파일을 자동으로 읽어 html파일을 빌드할 수 있게 해준다. (결과적으로 dist폴더 내에 들어가게 된다.) 컴파일이나 번들링 등 빌드된 파일 이름에 해시가 포함된 경우 유용하다.

npm i -D html-webpack-plugin

1 webpack.config.js

const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
   entry: './js/main.js',
    output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  },

  // 번들링 후 결과물의 처리 방식 등 다양한 플러그인들을 설정
  plugins: [
    new HtmlPlugin({
      template: './index.html'
    })
  ],

  devServer: {
    host: 'localhost'
  }
}

 

copy-webpack-plugin

디렉토리를 카피하여 dist에 들어갈 수 있도록 설정하는 플러그인이다.

이미지, 파비콘과 같은 정적 파일은 하나의 디렉토리에 넣어 빌드하면 편하다. 

npm i -D copy-webpack-plugin

1 webpack.config.js

const CopyPlugin = require('copy-webpack-plugin')
//
plugins: [
    new HtmlPlugin({
      template: './index.html'
    }),
    new CopyPlugin({
      patterns: [
        { from: 'static' } // static폴더로부터
      ]
    })
  ],

 

CSS와 SCSS

css-loader, style-loader, sass-loader, sass

css-loader : js파일에서 css파일을 불러들이도록 도와주는 플러그인

style-loader : html파일의 style안 으로 css를 삽입해주는 역할

sass-loader : js파일에서 scss파일을 불러들이도록 도와주는 플러그인

npm i -D css-loader style-loader
npm i -D sass-loader sass

1 webpack.config.js

  module: {
    rules: [
      {
        test: /\.s?css$/, // scss혹은 css확장자 파일 찾기
        use: [
          'style-loader', // 작성 순서가 중요
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  }

2 main.js

import '../scss/main.scss'

*module은 css, scss, babel등을 불러읽어 들어올 수 있도록 webpack-loader설정을 추가해주는 부분이다.

 

 

postcss, autoprefixer, loader

postcss(스타일에 후처리를 도와주는 패키지)를 사용하여 autoprefixer(공급업체접두사를 자동으로 붙여주는 플러그인)을 사용, webpack에서 postcss를 동작하게 해주는 postcss-loader

npm i -D postcss autoprefixer postcss-loader

1 webpack.config.js

*작성 순서 중요

module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [  'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ]
      }
    ]
  },

2 package.json

autoprefixer를 사용할 때는 browserslist를 꼭 작성해줘야 함

  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]

3 .postcssrc.js

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

 

babel

npm i -D @babel/core @babel/preset-env @babel/plugin-transform-runtime babel-loader

1 webpack.config.js

        test: /\.js$/,
        use: [
          'babel-loader'

2 .babelrc.js

module.exports = { 
  presets: ['@babel/preset-env'], 
  plugins: [ 
    ['@babel/plugin-transform-runtime'] 
  ] 
}

 

 

build 결과

dist폴더 내에 연결된 파일들이 불러들여와진다.

 

 

 


webpack.config.js 전체 내용

const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
   entry: './js/main.js',
    output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  },

  module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ]
      },
      {
        test: /\.js$/,
        use: [ 'babel-loader' ]
      }
    ]
  },

  plugins: [
    new HtmlPlugin({
      template: './index.html'
    }),
    new CopyPlugin({
      patterns: [
        { from: 'static' }
      ]
    })
  ],

  devServer: {
    host: 'localhost'
  }
}

 

728x90
+ Recent posts