본문 바로가기

서버/Webpack

Webpack - 간단하게 js파일 에서 이미지를 import 후 웹팩에서 파싱하기

728x90

개요)

js파일에서 img를 import 하고나서 

해당 이미지를 

변수에 담아서 사용하려고 한다.

 


1. [실습 전 셋팅]

 

1-1. webpack 설치

npm i webpack webpack-cli --save-dev

 

1.2.디렉토리 구조

 

folder

->index.html

->add-image.js

->webpack.config.js

 


 

1.3. 소스 추가하기

 

kiwi.jpg(아무 이미지 상관없음)

 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./dist/bundle.js"></script>
</body>
</html>

 

add-image.js

import Kiwi from './kiwi.jpg';

function addImage() {
    const img = document.createElement('img');
    img.alt = 'kiwi';
    img.width = 300;
    img.src = Kiwi;

    const body = document.querySelector('body');
    body.appendChild(img);
}

export default addImage;

 

 

webpack.config.js

// can't use ecma script module. use only common.js
console.log("module >>> ", module);
const path = require('path');

// minimum option
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist')
    },
    mode: 'none',
    module: {
        /**
         * webpack: I don't know what that menas 'import Kiwi...'
         * me: thank you for asking, If you don't know somethig, you should check out the rules.
         * webpack: perfect
         */
        rules: [
            {
                test: /\.(png|jpg)$/,
                type: 'asset/resource'
            }
        ]
    }
}

 

* rules: 웹팩이 파싱하며 빌드할 때 js,css,html 이외 파일이 있는 경우 해당 룰을 확인하여 처리한다.

* test: 정규식을 통해 웹팩이 알 수 없는 파일과 일치하는지 확인한다.

* type: 해당 내용을 어떤 타입으로 처리할지 타입을 정한다.

 


2. 빌드하기

npx webpack

 

빌드 하고 나면 다음과 같은 디렉토리가 생성됨

 

 

 


3. index.html을 열어보기

 

index.html에는 미리 빌드한 js파일을 넣어주었다.

 

index.html을 열어

이미지가 들어오는지 확인해보자

 

 

path 한 URL을 

브라우저에 넣어주기

 

잘 들어온다.