서버/Webpack
Webpack - vue, react처럼 component 직접 만들어보기
탐훈
2024. 10. 28. 12:22
728x90
개요)
component화 된
프론트 프레임워크인 react, vue 처럼
웹팩만을 이용해 컴포넌트화 작업을 할 수 있도록
만들어보기
[1. 디렉토리 구성]
[2. 소스]
[hello-world-button.css]
.hello-world-button {
font-size: 20px;
padding: 7px 15px;
background: green;
color: white;
outline: none;
}
[hello-world-button.js]
import './hello-world-button.css'
class HelloWorldButton {
render() {
const button = document.createElement('button');
button.innerHTML = 'Hello World';
button.classList.add('hello-world-button');
button.onclick = function() {
const p = document.createElement('p');
p.innerHTML = 'Hello World';
p.classList.add('hello-world-text');
body.appendChild(p);
}
const body = document.querySelector('body');
body.appendChild(button);
}
}
export default HelloWorldButton;
[index.js]
import HelloWorldButton from "./components/hello-world-button";
const helloWorldButton = new HelloWorldButton();
helloWorldButton.render();
[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>
[package.json]
{
"scripts": {
"build": "webpack"
},
"devDependencies": {
"webpack": "^5.95.0",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"css-loader": "^7.1.2",
"style-loader": "^4.0.0"
}
}
[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$/,
type: 'asset/source'
},
{
// loader should be installed explicitly
test: /\.css$/,
use: [
'style-loader', 'css-loader'
]
}
]
}
}
[4. npm package 중 css 관련 추가]
npm install css-loader style-loader --save
[5. 설명]
이전에 포스팅 올렸던
asset에 대한 처리는 webpack에 내장되어 있다.
css에 대한 처리는
내장되어 있지 않아 따로 설치해야 한다
webpack 설정파일에 있는
엔트리 포인트로 시작하여
js파일 내에 import 된 내용들을
javascript화 시켜서
bundle해준다.
결과를 보면
<head> 태그 아래에
<style> 태그가 자동으로 주입되어 있는 걸 확인할 수 있다.