webpack basic with webstorm

webstorm 프로젝트 생성

File > New > Project > Empty

프로젝트 생성이후 아래 위치로 들어가서

settings>Language&Frameworks>Node.js and NPM

아래와 같은 node 설정을 해준다

사용 node version 정보

  • nodejs version : 6.16.0
  • npm version : 3.10.10

npm module install

  • webpack
  • webpack-cli
  • lodash

상위 세팅이 완료된 이후

npm init

실행을 통해서 package.json을 생성해 준다

이후 기본 webpack 구조를 다음과 같이 만들어 준다

webpack project 기본 구조

  webpack-demo
  |- package.json
+ |- /src
+   |- index.js
+ |- /dist
+   |- index.html

해당 파일별 내용은 다음과 같다

dist/index.html

<!doctype html>
<html>
<head>
    <title>Getting Started</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

src/index.js

import _ from 'lodash'

function component() {
    let element = document.createElement('div');

    // Lodash, currently included via a script, is required for this line to work
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
}

document.body.appendChild(component());

webpack 설정

webpack.config.js 설정

webpack을 실행하기 위해서는 기본적으로 config file이 필요하다. 아래와 같이 javascript파일을 생성해 준다

  webpack-demo
  |- package.json
  |- /src
    |- index.js
  |- /dist
    |- index.html
+ |- webpack.config.js

해당 config에 다음과 같이 코드를 넣어 준다.

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    }
};

entry는 webpack 처리할 최초 javascript의 위치를 지정하고, 해당 지정된 js를 바탕으로 webpack 처리(통합처리)될 파일을 산출할 위치를 output으로 표현해 준다.

webpack 실행

config파일까지 작성이 완료 되었다면, 다음 커멘드를 comand 창에서 실행한다.

webpack --config webpack.config.js

build가 완료 되면 dist/main.js가 생성되고 생성된 해당 파일에는 lodash와 index.js가 하나의 파일로 합쳐져 있는것을 확인 할 수 있다.

NPM Script

NPM을 이용한 build

webpack 명령어를 이용한 빌드의 경우 매번 해당 커멘드를 작성해야하는 번거로움이 있다. 이를 해결하기 위해 아래와 같이 npm을 이용한 빌드를 설정한다

package.json

{
  "name": "untitled1",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "dependencies": {
    "webpack": "^4.29.3",
    "webpack-cli": "^3.2.3",
    "lodash": "^4.17.11"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
+    "build" : "webpack --config webpack.config.js"
  },
  "author": "",
  "license": "ISC"
}

상위 코드를 입력한 후 다음 명령어를 실행한다.

npm run build

webstorm에서는 "build" 왼쪽으로 나타나는 ▶ 표시를 클릭해서 실행 해도 문제가 없다.

Asset file 통합

CSS 파일

css 파일을 통합하기 위하여 css의 위치와 해당 css 로드시 사용할 node 모듈을 install 해야 한다

npm module install
  • sytle-loader
  • css-loader

모듈 인스톨 이후 style.css를 다음과 같이 만들어 준다

  webpack-demo
  |- package.json
  |- /src
    |- index.js
  |- /dist
    |- index.html
+   |- style.css

style.css

.hello {
    color: red;
}

해당 파일을 webpack에서 읽어 올 수 있도록 config를 설정 한다.

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    },
+    module: {
+        rules:[
+            {
+                test: /\.css$/,
+                use: [
+                    'style-loader',
+                    'css-loader'
+                ]
+            }
+        ]
+    }
};

module의 Rule은 2가지로 이루어 진다

  1. 리소스 : test,include,exclude, resource tag로 설정 가능하고, 정규화 식을 사용한다. 단, test와 resource tag는 혼용 할 수 없다
  2. 발행자(issuer) : 발행자의 경우는 entry인 index.js에 import 처리 하면 output 파일에 bundle 된다

use의 경우 로드된 리소스를 처리하는 모듈을 지정할 수 있다. 지정된 모듈은 chained되게 연속적으로 실행 되지만, 주의할 점은 실행의 순서가 맨 마지막에서 처음으로 로드된다는 것이다. 여기서는 'css-loader' 이후에 'style-loader'가 실행 된다.

issuer 처리를 위해서 다음 코드를 추가한다

src/index.js

import _ from 'lodash'
+ import './style.css'

function component() {
    let element = document.createElement('div');

    // Lodash, currently included via a script, is required for this line to work
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
+    element.classList.add('hello');
    return element;
}

document.body.appendChild(component());

issuer인 import './style.css'를 entry에 표현 하지 않으면 해당 css 파일은 build시 bundle 제외 된다.

Image 파일

npm module install
  • file-loader

모듈 인스톨 완료 후에 적당한 이미지를 다음과 같이 프로젝트에 추가해 준다.

  webpack-demo
  |- package.json
  |- /src
    |- index.js
  |- /dist
    |- index.html
    |- style.css
+   |- icon.png

해당 파일을 로드하기 위해 아래와 같이 webpack config를 수정해 준다.

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
+            {
+                test:/\.(png|svg|jpg|gif)$/,
+                use :[
+                    'file-loader'
+                ]
+            }
        ]
    }
};

해당 이미지 issuer를 등록한다.

src/index.js

import _ from 'lodash'
import './style.css'
+ import Icon from './icon.png';

function component() {
    let element = document.createElement('div');

    // Lodash, currently included via a script, is required for this line to work
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');

+    var myIcon = new Image();
+    myIcon.src = Icon;
+    element.appendChild(myIcon);

    return element;
}

document.body.appendChild(component());

이 정도로 해당 icon.png는 bundle되게 된다. 그러나 만약에 해당 png를 entry에서 로드 하지 않고 css에서만 사용한다고 해도 entry가 style을 부르고 style에서 icon.png를 부르기 때문에 bundle처리 된다.

src/style.css

.hello {
    color: red;
+    background: url('./icon.png');
}

기타 파일

상위의 경우와 마찬가지로 각종 Asset을 로드 할 수 있는데, 로드가 가능한 모듈과 리소스는 다음과 같다

기타 npm module install
  • file-loader : font 및 각종 리소스 자료
  • csv-loader : csv, tsv 등
  • xml-loader : xml

Output Management

다중 Entry

만약에 entry에 대상이 되는 js가 한개 이상일 경우 어떻게 셋팅해야 하는지 알아본다

 webpack-demo
  |- package.json
  |- /src
    |- index.js
+   |- print.js 
  |- /dist
    |- index.html
    |- style.css
    |- icon.png

새로운 javascript를 하나 추가 하였다. 해당 javascript에는 다음 내용이 들어간다

src/print.js

export default function printMe() {
    console.log('I get called from print.js!');
}

해당 entry를 webpack config에 등록해 준다.

webpack.config.js

const path = require('path');

module.exports = {
    entry: {
+        app: './src/index.js'
+        , print : './src/print.js'
    },
    output: {
        // filename: 'main.js',
+       filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test:/\.(png|svg|jpg|gif)$/,
                use :[
                    'file-loader'
                ]
            }
728x90
반응형

'Web' 카테고리의 다른 글

Web Components Callback Methods & lifecycle  (0) 2021.08.14
Web component (Custom Elements, Shadow DOM, Template)  (0) 2021.08.14
Gradle's dependency cache may be corrupt  (1) 2021.05.21
Vue basic with webstorm  (0) 2020.03.27
javascript object merge  (0) 2020.03.27