728x90


이제 scss를 css로 바꿔서 빌드해보도록하자.



프로젝트 구조는 위와 같다.


<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello</title>
</head>
<body>
<header>this is header</header>
<div><span>안녕하세요!</span></div>
<footer>this is footer</footer>
</body>
</html>

index.html은 뭐 특별한거 없는 일반 html파일이다.

하지만 이 파일이 안 중요한건 아니다.

이 파일은 여러분이 만들 결과 페이지이기 때문이다.

이 페이지에 css를 포함하고 싶을 건데 그걸 link태그로 포함해줄 필요가 없다!

그 이유는 아래를 보면 알 수 있다.


// index.js
import './style/main.scss';

index.js는 여러분이 최종 번들링으로 사용할 js인데 쌩뚱 맞게 여기에 사용할 scss를 추가시켜준다.

이게 뭔짓인가?? 라고 생각할 수있겠지만 webpack에서는 특별하게 설정하지 않는다면

js에 포함된 스타일(css,scss,sass,stylus)등을 합칠 때 바로 html에 박아버린다.

그렇기 때문에 위 처럼 사용한다.


//main.scss
div{
span{
background-color: red;
}
}

그리고 scss를 만든다. 문법도 scss로 만든다.


//package.json
"devDependencies": {
"css-loader": "^3.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.7.0",
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.6"
}

해당 모듈들을 다운로드해주자.


자 이제 웹팩 설정을 보자.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
entry: {
main: ['./src/index.js'],
},
output: {
filename: 'bundle.[contenthash].js',
path: path.join(__dirname, './dist'),
publicPath: '/dist'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css"
}),
],
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
]
},
]
}
};

길어 보이지만 사실 어려운 내용은 아니다 하나씩 보자.


entry: {
main: ['./src/index.js'],
},

엔트리포인트를 index.js로 해준다.

원래 webpack은 js번들러이므로 저번 같은 특이한 사항이 아니라면 원래는 js를 번역하기 위해서 사용한다.


output: {
filename: 'bundle.[contenthash].js',
path: path.join(__dirname, './dist'),
publicPath: '/dist'
},

내보내는 이름은 보통 bundle에 해시를 붙혀서 만든다.

publicPath라는게 추가됬는데 이는 보통때는 아무역활도 안하는데 html를 사용해서 내보내는 구조라면 의미를 가진다.

바로 html 내부에 사용하는 script,js의 경로에 publicPath를 붙혀주는 역활을 한다.


plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css"
}),
],

두개 중에 하나는 전 포스팅에서 설명하였고 아래는 css를 파일로 출력하는 플러그인이다.


module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
]
},
]
}

룰에서 scss파일을 만나면 

1.css출력플러그인을 로드하고

2.css로더를 로드하고

3.sass로더를 로드한다.

그리고 처리해서 css파일로 내보내게 된다.


webpack


이제 빌드 돌려보자.


그러면 번들링된 js, 그리고 js에서 사용되었던 css를 확인할 수있다.


main.scss는 성공적으로 빌드된걸 확인할 수 있다.



그리고 js와 css가 아무 설정을 해주지 않았는데도 달라붙은걸 확인할 수 있다.

HtmlWebpackPlugin은 entry로 빌드한 js를 바로 붙혀버리고 js에 포함되어있는 css들 역시 바로 붙혀버린다.


마지막으로 적용된걸 확인할 수 있다.

+ Recent posts