서버/Webpack

Webpack - txt를 빌드할 때 넣어보기

탐훈 2024. 10. 28. 12:04
728x90

개요) 

txt 파일의 텍스트를 

원하는 위치에 넣어주기 

 


1. [실습전 셋팅]

노드설치

webpack설치

(이전 포스팅에 방법 나와있음)

 

디렉토리 셋팅

src

- add-image.js

- altText.txt

- kiwi.jpg (아무사진 상관없음)

- index.js

index.html

webpack.config.js

 

 


[2. 소스]

 

[add-image.js]

import Kiwi from './kiwi.jpg';
import altText from './altText.txt';

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

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

export default addImage;

 

 

[altText.txt]

 ALT TEST NAME

 

 

[index.js]

import addImage from './add-image.js';
addImage();

 

 

[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>

 

[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'),
        /**
         * publicPath
         * under version 4: publicPath is empty('').
         * over version 4: publicPath is auto
         * 
         * can use list
         *      1. 'dist/'
         *      2. 'https://image.oliveyoung.co.kr/uploads/contents/202410/25oyDay/pc_visual.jpg'
         */
        publicPath: '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)$/,
                /**
                 * asset/inline  :bake image into base64. could be larger file size(more better)
                 * asset/resource: request image each of them. cost of call is larger
                 */
                type: 'asset',
                parser: {
                    dataUrlCondition: {
                        maxSize: 3 * 1024 // 3kilobyte
                    }
                }
            }
            {
                test: /\.txt$/,
                /**
                 * asset/inline  :bake image into base64. could be larger file size(more better)
                 * asset/resource: request image each of them. cost of call is larger
                 */
                type: 'asset/source'
            }
        ]
    }
}

 

 

[package.json]

{
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "webpack": "^5.95.0",
    "webpack-cli": "^5.1.4"
  }
}

 


[3. 빌드해서 확인해보기]

npm run build