티스토리 뷰

front-end/개발환경구축

Webpack 기초

kmj24 2021. 7. 22. 00:17

Module

exports키워드를 이용하여 모듈관리

//내보내기
module.exports = {
   module명1,
   module명2
}
exports.getCircleArea = module명3;

//가져오기
const module = require('모듈 위치');

ESM을 이용한 module관리

npm install esm

package.json에 "type": "module"추가

//가져오기
import module명 from '모듈위치';

//내보내기
export module명
export default

module을 사용할 경우 코드의 재사용성이 증가

코드의 관리가 편해짐

코드를 모듈화 하는 기준이 명확해야 한다.

 

Bundle

module들의 의존성을 안전하게 유지하며 하나의 파일로 묶는것을 bundle이라고 한다.

webpack은 이러한 module들을 모아 bundling하기 때문에 module bundler라고도 한다.

Bundle을 사용함으로써 얻을 수 있는 이점은

1. 모든 module을 로드하기 위해 검색하는 시간의 단축

2. 사용하지 않는 코드 제거

3. 파일의 크기를 줄여줌

Webpack

하나의 Application에 수많은 module로 구성되어 있고, module들은 복잡한 참조 관계를 형성.

module들에 대한 참조관계를 해석하여 의존성 그래프를 만든다.

Entry

  • 의존성 그래프를 만들기 위해 어떤 module을 시작점(entry point)으로 해석할지 결정
module.exports = {
   entry: './path/to/my/entry/file.js'
};

Output

  • Webpack이 생성하는 번들 파일에 대한 정보를 설정
const path = require('path');

module.exports = {
   entry: './path/to/my/entry/file.js',
   output: {
      paht: path.resolve(__dirname, 'dist'),
      filename: 'webpack.bundle.js'
   }
};

Mode

  • build환경을 'production'모드 또는 'development'로 설정하여 각 환경에 해당하는 webpack의 기본 제공 최적화를 한다.
  • 'production' | 'development' | 'none'으로 설정할 수 있다.
  • none은 기본 최적화 옵션을 제외한다.
  • Package.json
    • Application 내부에 직접 포함되는 모듈
    • 개발과정에 필요한 module을 작성
    • dependencies : application에 직접적으로 포함되는 모듈, --save
    • devDependencies : 개발 과정에 포함되는 모듈, --save-dev

Loader

  • 다양한 모듈들을 입력받아 처리하는 역할
  • javascript파일이나 json파일을 기본 module로 사용한다.
  • 다른 파일(css파일 등)을 사용해야 될 경우 loader를 설정해야 한다.
module.exports = {
   module: {
      rules: [loader1, loader2]
   }
}

Plugin

Webpack이 동작하는 과정에서의 개입을 통해 여러가지 역할 담당

 - 번들 파일 변화

 - 개발 편의성 제공

 - 프로덕션 모드 코드 최적화 등 

module.exports = {
   plugins: [new Plugin({...option}, ...)]
}

 

webpack 실습

1. package.json 파일 생성

npm init -y

2. webpack 설치 

npm install webpack webpack-cli --save-dev

2. index.html파일 생성

<script src="./dist/bundle.js"></script>

3. index.js 파일 생성

4. index.js에 로직 작성

5. webpack.config.js 파일 생성

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist')
    },
    mode: 'none'
}

6. package.json의 script에 내용 추가

"scripts": {
   "build": "webpack"
},

7. 터미널에서 실행

index.js(entry)에서 설정한 로직이 ./dist/bundle.js(ouput)에 생성된다.

npm run build

build 성공

 

8. style-loader, css-loader 적용

css-loader : css를 module로 다루기위해 사용

style-loader : css-loader를 통해 가져온 css를 style tag를 생성하여 head tag 안에 주입한다.

npm install style-loader css-loader --save-dev

9. wepback.config.js파일을 수정한다.

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader'
                    }
                ]
            }
        ]
    },
    mode: 'none'
}

test는 어떤 파일들이 loader의 대상이 되는지에 정규표현식을 통해 패턴 매칭으로 설정할 수 있다.

use는 사용하는 loader를 지정하는 loader key와 loader의 동작을 변경하는 options key가 있다.

css파일을 module로 다룰 수 있는 환경이 완성 되었다.

 

10. css파일을 module로 불러와서 적용

style작업 시 브라우저 마다 다르게 적용이 되는 문제가 있을 수 있다.

user agent style을 통일시켜야 한다.

방법1. reset.css 사용

 - 적용 된 스타일을 제거

방법2. normalize.css

 - 적용 된 스타일 중 다르게 작동하는 style구문들만 같게 만들어 준다.

normalize.css 사용

npm install normalize.css --save

11. index.css를 만들고 index.js에 normalize.css와 index.css를 import

import 'normalize.css';
import './index.css';

12. 프로젝트를 빌드하면

head tag내 normalize.css가 적용됨

13. css module설정

설정방법

https://github.com/webpack-contrib/css-loader

 

GitHub - webpack-contrib/css-loader: CSS Loader

CSS Loader. Contribute to webpack-contrib/css-loader development by creating an account on GitHub.

github.com

 

options의 내용

modules가 css모듈에 대한 설정을 담당한다.

modules옵션을 true로 하여 css 모듈을 사용하도록 설정한다.

webpack.config.js의 use배열에 loader와 modules옵션을 설정한다.

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options:{
                            modules: true
                        }
                    }
                ]
            }
        ]
    },
    mode: 'none'
}

그럼 이제 css모듈을 사용할 수 있게 된다.

//index.css
.helloWebpack{
    color: blue;
}

//index.js
import styles from './index.css';
element.classList = styles.helloWebpack;

styles를 출력해보면 css파일의 classname이 object의 key로 적용이 되고, value는 hash값으로 나온다.

styles의 내용

css는 선택자의 이름(id, classname 등)이 전역으로 적용되기 때문에 전체 application에서 중복되지 않도록 주의해야 하지만 css module을 사용함으로써 이를 해결할 수 있다.

 

14. style-loader 적용

webpack.config.js의 use배열에 loader와 options를 설정한다.

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    {
                        loader: 'style-loader',
                        options: {
                            injectType: 'singletonStyleTag'
                        }
                    },
                    {
                        loader: 'css-loader',
                        options:{
                            modules: true
                        }
                    }
                ]
            }
        ]
    },
    mode: 'none'
}

그리고 build를 한다

그러면 css modules가 적용된 하나의 style tag만 적용된다.

 

15. plugin 설치

html-webpack-plugin를 사용한 예시이다.

npm install html-webpack-plugin --save-dev

16. plugin 설정

webpack.config.js에 html-webpack-plugin에 대한 내용을 설정한다.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './index.js',
    output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    {
                        loader: 'style-loader',
                        options: {
                            injectType: 'singletonStyleTag'
                        }
                    },
                    {
                        loader: 'css-loader',
                        options:{
                            modules: true
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './template.html'
        })
    ],
    mode: 'none'
}

html webpack plugin에 대한 설정은 여기에 있다.

https://github.com/jantimon/html-webpack-plugin

 

GitHub - jantimon/html-webpack-plugin: Simplifies creation of HTML files to serve your webpack bundles

Simplifies creation of HTML files to serve your webpack bundles - GitHub - jantimon/html-webpack-plugin: Simplifies creation of HTML files to serve your webpack bundles

github.com

template옵션은 자동으로 생성되는 html문서가 설정한 파일 기준으로 생성되도록 설정하는 옵션이다.

template.html을 지정해 주었기 때문에 기존의 index.html을 template.html로 변경하고 아까 작성한

script태그를 지운다.

그리고 build

dist 폴더 아래에 index.html이 생긴다.

webpack.config.js의 output에 설정된 내용으로 리소스를 불러올 수 있도록 script또는 link태그를 추가해준다.

script태그를 지웠지만 dist폴더 아래에 생성된 index.html파일에는 script태그가 설정되어 있다.

 

'front-end > 개발환경구축' 카테고리의 다른 글

url-loader 설정  (0) 2021.07.29
file loader 설정  (0) 2021.07.29
Development mode & Production mode  (0) 2021.07.27
webpack 소스 코드 최적화  (0) 2021.07.26
webpack Caching 설정  (0) 2021.07.26
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함