output 설정하기

SPANKEEE·2022년 1월 4일
0

웹팩

목록 보기
5/7

우리는 당연히 하나의 페이지만 제작을 하지 않을 것이다.

일단은 임시로 about.html 파일을 제작하고, index.html파일을 수정한다.

<html>
    <body>
        <h1>Hello webpack! | About</h1>
        <div id="root"></div>
        <script src="public/about_bundle.js"></script>
        <a href="./index.html">go to index</a>
    </body>
</html>
  • about.html
    about 페이지는 source폴더 내에 index_bundle.js가 아닌 about_bundle.js파일을 사용한다.
<html>
    <body>
        <h1>Hello webpack! | index</h1>
        <div id="root"></div>
        <script src="public/index_bundle.js"></script>
        <a href="./about.html">go to about</a>
    </body>
</html>
  • index.html
import hello_word from './hello.js';
// 수입하다 변수명 어디서? 해당루트
import world_word from './world.js';
// 수입하다 변수명 어디서? 해당루트
import css from './style.css';
// 수입하다 변수명 어디서? 해당루트
document.querySelector('#root').innerHTML =  'this page is about';
// 도큐먼트에 요소선택(아이디태그 root).HTML내 내용추가
console.log('css', css);
// 콘솔로그를 통해 css를 번들링 했는지 확인
  • about_bundle.js 생성

설정파일 config.webpack.js 수정

index.js파일과 about.js파일을 번들링 하고 싶을때는
모듈 도입 부분(entry)를 수정한다.

그리고 output객체 내에 있는 filename : 이 부분을

  • filename : [name]_bundle.js 로 수정한다.
const path = require('path');
// 파일의 경로를 쉽게 핸들링 해줄 수 있게 도와주는 일종의 부품이라 생각한다.

module.exports = {
    mode: "development",
    //개발
    entry: {
        // 여러 자바스크립트를 나열
        index : "./source/index.js",
        about : "./source/about.js"
    },
    // 도입할 .js 위치
    output: {
        path: path.resolve(__dirname,"public"),
        // dist 라는 하위 경로에 최종적인 경과물을 "public"에 놓아라
        filename: '[name]_bundle.js'
        // 번들링 될때 파일 명을 해당 entry의 이름에 맞게 번들링 해준다.
    },
    module: {
        rules:[
            // 모듈을 처리하는 규칙 
            {
                test: /\.css$/,
                // 웹팩을 통해서 가공하는 여러가지 데이터중 CSS확장자 파일 처리하는 방식을 알려주고 싶다
                use: ['style-loader', 'css-loader']
                // 웹팩을 동작시켰을때 확장자가 CSS인 파일을 만나면 웹팩이 알아서 해당 CSS파일을 웹팩 안으로 로드시켜준다.
            }
        ]
    }
}

터미널에 아래 명령어를 입력

npx webpack

index.html

  • public폴더 내에 index_bundle.js가 사용되는 것을 확인할 수 있다.
    이제 go to about을 눌러 about페이지로 이동해 보자

about.html

  • public폴더 내에 about_bundle.js가 사용되는 것을 확인할 수 있다.

이로써 각 페이지에 올바르게 적용되는 자바스크립트를 번들링 할 수 있다.

profile
해야되요

0개의 댓글