
Webpack Getting Started를 한글로 번역하면서 기본적인 사용법에 대해 알아보는 시간입니다.
webpackis used to compile JavaScript modules. Once installed, you can interface with webpack either from itsCLIor API.
webpack 설치 devDependencies로 설치하자
webpack을 좀 더 매니악하게 커스텀해줄 수 있는 툴이 있는데, 바로 webpck-cli 이다. 필요하면 이것도 devDependecies로 설치하자. Webpack3 까지는 webpack 만 설치해도 됬었는데 Webpack4부터는 webpack-cli 을 같이 설치해야 커맨드라인에 webpack 이라는 명령어를 사용할수 있다.
npm i -D webpack webpack-cli
First we'll tweak our directory structure slightly, separating the "source" code (
/src) from our "distribution" code (/dist). The "source" code is the code that we'll write and edit. The "distribution" code is the minimized and optimizedoutputof our build process that will eventually be loaded in the browser.
With that said, let's runnpx webpack, which will take our script atsrc/index.jsas the entry point, and will generatedist/main.jsas the output. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package we installed in the beginning:
npx webpack 실행과정npx webpack 명령어는 ./src/index.js 를 엔트리 포인트로 삼고./dist 폴더가 생성되고 그 아래에 main.js라는 이름으로 번들이 생성한다.npx webpack으로 번들을 생성할 때 해야 할 일[첫 번째]. 다음과 같은 디렉터리 구조를 만들어둬야 한다.
webpack-demo
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
[두 번째]. ./src/index.js를 기준으로 필요한 것들을 improt ~~ from '경로' 로 정의해서 사용하면 된다.
[세 번째]. npx webpack을 구동하면, 번들된 js파일 main.js가 dist 디렉토리에 생성될 것이다. 번들이 생성되면, ./dist/index.html 에서 수 많은 script 태그들은 필요가 없어지고 번들만을 script 태그로 가져오면 된다는 것이다.
webpack actually "transpiles" the code so that older browsers can also run it. If you inspect dist/main.js, you might be able to see how webpack does this, it's quite ingenious! Besides import and export, webpack supports various other module syntaxes as well, see Module API for more information. → https://webpack.js.org/api/module-methods/
웹팩은 코드를 "트랜스 파일"한다. 따라서 옛날 버전의 브라우저에서도 최신 Javascript 문법의 사용이 가능해진다. 또한, webpack은 다른 모듈의 구문을 지원한다. 지원하는 module들에 대한 정보는 링크에서 찾아보면 된다. https://webpack.js.org/api/module-methods/
트랜스파일이란?
컴파일은 한 언어로 작성된 소스 코드를 다른언어로 변환하는 것을 의미합니다. C언어로 작성된 소스코드를 기계어로 변환하는 과정
트랜스파일은 한 언어로 작성된 소스코드를 비슷한 수준의 추상화(Abstraction)를 가진 다른 언어로 변환하는 것을 말합니다.
C#으로 작성된 소스코드를 컴파일하면 소스코드와 기계어 사이의 중간 단계 언어(IL, Intermediate Language)로 변하는데, 이때 두 언어는 서로 매우 다른 추상화 수준을 가지고 있습니다. 그렇기 때문에 이 경우, 트랜스파일링(transpiling)했다고 말하지 않습니다. 만약 TypeScript 로 작성된 코드를 컴파일하면 JavaScript 코드로 변환되는데요. 이 두 언어간의 추상 수준은 매우 비슷합니다. 이 때에는 트랜스파일링했다라고 표현합니다.
참고자료 : https://ooz.co.kr/416
Note that webpack will not alter any code other than
importandexportstatements. If you are using other ES2015 features, make sure to use a transpiler such as Babel or Bublé via webpack's loader system.
그러나 모든 최신 문법을 트랜스파일 해주는 것은 아니다. webpack은 import와 export 문의 코드만을 변경한다. ES2015 기능을 사용하는 경우 웹펙의 로더 시스템을 사용해서 babel과 같은 트랜스 파일러를 불러와야 한다.
Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is src/index.js and will output the result in dist/main.js minified and optimized for production.
webpack은 기본적으로 config 파일을 필요로 하진 않는다. 그러나 config 파일이 없으면, entry point는 무조건 ./src/index.js 여야 하며, output의 경로는 ./dist/main.js 여야 한다.
Usually your projects will need to extend this functionality, for this you can create a webpack.config.js file in the root folder and webpack will automatically use it.
webpack.config 파일을 작성해서 루트 디렉터리에 두고 run 하면 알아서 읽어간다.
프로젝트 규모가 다르고 디렉토리 구조도 다 다른데, Webpack을 위한 디렉터리 구조를 어떻게 계속 유지할 수 있겠는가, 따라서 Webpack은 webpack configuration file을 통해 npx webpack을 사용하기 위해 고정된 디렉터리 구조를 사용할 필요가 없게끔 만들었다. 좀 더 세밀하고 프로젝트에 적합한 설정을 위해, 또 유연한 디렉터리 구조를 사용하기 위해 Webpack Config file을 사용해보자.
As of version 4, webpack doesn't require any configuration, but most projects will need a more complex setup, which is why webpack supports a configuration file. This is much more efficient than having to manually type in a lot of commands in the terminal, so let's create one:
루트 디렉토리에 webpack.config.js 생성
webpack.config.js가 존재하면, webpack은 알아서 그걸 default로 삼고 가져간다.
--config 옵션이 존재, 번들을 여러개로 나누고자 하는 프로젝트에서는 웹팩 config 파일이 여러개 존재할 것이다. 여러개의 config 파일 중 하나를 골라서 run 하고 싶을 때 이 옵션을 사용하면 된다. EX) npx webpack --config webpack.config.js
webpack.config.js 작성
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
위와 같이, module.export를 해야한다.
Now the
npm run buildcommand can be used in place of the npx command we used earlier. Note that within scripts we can reference locally installed npm packages by name the same way we did with npx. This convention is the standard in most npm-based projects because it allows all contributors to use the same set of common scripts (each with flags like --config if necessary).
훗날, 복잡한 프로젝트 구조로 config 옵션을 사용할 때가 올거야.
그럼 build 할 때마다, npx webpack --config 어쩌구.config.js를 입력해주기 번거로우니 package.json의 script를 사용하자.
(예를 들어, "build": "webpack --config prod.config.js" 라는 명령어 계속 치고 있기에는 좀...)
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
위 코드 처럼 "build"라는 script를 작성하면, npx webpack 대신 npm run build로 번들을 생성 할 수 있다. 뭐 config 옵션을 적어야 할 때도 script를 변경해주면 간단하게 쓸 수 있다.
("build": "webpack --config prod.config.js"로 작성해주면 이제, npm run build만으로도 긴 명령어를 대체할 수 있다.)
옵션들은 CLI의 인자로도 넘길 수 있다.
ex) webpack --mode=development
이번 포스트는 웹팩의 기본에 대해 알아봤습니다. 옵션은 너무 많고 어렵기 때문에, 차근차근 포스트하겠습니다.