webpack 튜토리얼
webpack 시작하기
수색…
비고
Webpack은 의존성이있는 모듈을 읽고 해당 모듈을 나타내는 정적 자산을 생성하는 모듈 묶기입니다.
번들에 자바 스크립트 애셋뿐만 아니라 CSS, 이미지, HTML 등을 포함 할 수있는 확장 가능한 로더 시스템 이 있습니다.
예를 들어, 내장 된 자바 스크립트 로더 인 css-loader 와 url-loader를 사용하면 다음과 같습니다.
require("./code.js") // Load Javascript dependency
var css = require("./styles.css"); // Load CSS as a string
var base64Image = require("./image.png"); // Load an image as a base64 string
묶인 단일 파일이 될 것입니다 :
// From code.js
console.log("Hello, World");
// From styles.css
var css = "body { margin: 0; padding: 0; } h1 { color: #FF0000; }";
// From image.png
var base64Image = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX...";
의존성은 가장 일반적인 모듈 스타일 (CommonJS & AMD)에서 정의 할 수 있습니다.
버전
번역 | 출시일 |
---|---|
3.0.0 | 2017-06-19 |
2.6.1 | 2017-05-25 |
2.6.0 | 2017-05-23 |
2.5.1 | 2017-05-07 |
2.5.0 | 2017-05-04 |
2.4.1 | 2017-04-14 |
2.4.0 | 2017-04-14 |
1.13 | 2016-04-17 |
1.12 | 2015-08-25 |
1.11 | 2015-08-06 |
1.10 | 2015-06-27 |
1.9 | 2015-05-10 |
1.8 | 2015-04-29 |
1.7 | 2015-03-11 |
1.6 | 2015-02-24 |
1.5 | 2015-01-21 |
1.4 | 2014-12-28 |
1.3 | 2014-08-25 |
1.2 | 2014-05-27 |
1.1 | 2014-05-17 |
1.0 | 2014-03-01 |
0.11 | 2013-12-31 |
0.10 | 2013-06-19 |
0.9 | 2013-03-19 |
0.8 | 2013-01-21 |
설치
선수 과목 :
Webpack을 설치하는 방법은 전역 또는 프로젝트별로 두 가지가 있습니다. 프로젝트마다 의존성을 설치하는 것이 가장 좋습니다. 이렇게하면 각 프로젝트마다 서로 다른 버전의 웹팩을 사용할 수 있으며 사용자가 웹팩을 전 세계적으로 설치하지 않아도됩니다.
프로젝트 별 설치
프로젝트의 루트 폴더에서 다음 명령을 실행하십시오.
npm install webpack --save-dev
그런 다음에 설치 웹팩 실행 실행할 수 있습니다 node_modules
:
./node_modules/.bin/webpack
또는 package.json
파일에서 node_modules
부분을 생략 할 수있는 NPM 스크립트를 만듭니다. npm은 PATH에 해당 폴더를 포함 할 정도로 스마트합니다.
// in package.json:
{
...
"scripts": {
"start": "webpack"
},
...
}
// from terminal:
npm start
전 세계적으로 설치
프롬프트에서 다음 명령을 실행하십시오.
npm install webpack -g
babel이있는 webpack.config.js의 예
종속성
npm i -D webpack babel-loader
webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: ['babel-polyfill', './src/'],
},
output: {
path: __dirname,
filename: './dist/[name].js',
},
resolve: {
extensions: ['', '.js'],
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
include: path.resolve(__dirname, 'src')
}],
}
};
Javascript + CSS + 글꼴 + 이미지 예제
필수 모듈
npm install --save-dev webpack extract-text-webpack-plugin file-loader css-loader style-loader
폴더 구조
.
└── assets
├── css
├── images
└── js
webpack.config.js
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const glob = require('glob');
module.exports = {
entry: {
script: path.resolve(__dirname, './assets/js/app.js'),
style: path.resolve(__dirname, './assets/css/app.css'),
images: glob.sync(path.resolve(__dirname, './assets/images/**/*.*')),
},
context: __dirname,
output: {
path: path.resolve('./dist/assets'),
publicPath: '/dist/assets',
filename: '[name].js',
},
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
}),
},
{
test: /(\.woff2?|\.woff|\.ttf|\.eot|\.svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader?name=[name]-[hash:6].[ext]',
},
{
test: /\.(png|jpe?g|gif|ico)$/,
loader: 'file-loader?name=[name].[ext]',
},
],
},
plugins: [
new ExtractTextPlugin('app.css' /* optional: , { allChunks: true } */),
],
};
glob.sync('./assets/images/**/*.*')
는 이미지 폴더의 모든 파일을 항목으로 요구합니다.
ExtractTextPlugin
은 생성 된 출력을 가져 ExtractTextPlugin
번들 된 css
파일을 만듭니다.
Webpack 간단한 예제
Webpack을 사용하는 데 필요한 최소값은 다음과 같습니다.
webpack ./src/index.js ./dist/bundle.js
// this is equivalent to:
webpack source-file destination-file
웹 팩은 소스 파일을 가져 와서 출력 대상으로 컴파일하고 소스 파일의 모든 종속성을 해결합니다.
Webpack, React JSX, Babel, ES6, 간단한 구성
올바른 npm 의존성을 설치했는지 확인하십시오 (babel은 "peer dependencies"와 관련된 패키지 묶음으로 분리하기로 결정했습니다).
npm install webpack webpack-node-externals babel-core babel-loader babel-preset-react babel-preset-latest --save
webpack.config.js
:
module.exports = {
context: __dirname, // sets the relative dot (optional)
entry: "./index.jsx",
output: {
filename: "./index-transpiled.js"
},
module: {
loaders: [{
test: /\.jsx$/,
loader: "babel?presets[]=react,presets[]=latest" // avoid .babelrc
}]
}, // may need libraryTarget: umd if exporting as a module
externals: [require("webpack-node-externals")()], // probably not required
devtool: "inline-source-map"
};
webpack-node-externals
는 node_modules
를 스캔하고 프런트 엔드 코드와 함께 번들로 묶이지 않고 번들로 묶음을 보장하는 기능입니다. 이렇게하면 라이브러리를 다시 인코딩하지 않으므로 신속하게 번역 할 수 있습니다.
Node.js로 간단한 웹팩 설정
폴더 구조
.
├── lib
├── modules
| ├── misc.js
| ├── someFunctions.js
├── app.js
├── index.html
├── package.json
├── webpack.config.js
└── webserver.js
package.json
{
"name": "webpack-example-with-nodejs",
"version": "1.0.0",
"description": "Example using webpack code-splitting with some Node.js to support the example",
"main": "webserver.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "@Gun",
"license": "ISC",
"devDependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"http": "0.0.0",
"morgan": "^1.8.1",
"multer": "^1.3.0",
"webpack": "^2.4.1"
}
}
webpack.config.js
var path = require('path'); // used to get context
module.exports = {
context: path.join(__dirname, 'app'), // resolves entry below, must be absolute path
entry: './app.js', // entry point or loader for the application
output: {
path: path.join(__dirname, 'app/lib'), // express static folder is at /app/lib
filename: '[name].bundle.js', // the file name of the bundle to create. [name] is replaced by the name of the chunk (code-splitting)
publicPath: 'static' // example uses express as the webserver
}
};
webserver.js
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
multer = require('multer')()
logger = require('morgan'),
fs = require('fs'),
http = require('http');
var app = express();
var port = 31416;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('short'));
app.use('/jsBundles',express.static('lib'));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
var server = http.createServer(app).listen(port, function(){
console.log("I feel a disturbance in the port:" + port);
});
index.html
<!DOCTYPE html>
<html>
<body>
<div id="someValue"><label for="num">Enter a number:</label><input id="num" /></div>
<div class="buttonList">
<ul>
<li><button id="doubleIt">double it</button></li>
<li><button id="tripleIt">triple it</button></li>
</ul>
</div>
<div id="someOtherValue">
And the count shall be: <span id="theCount"></span>
</div>
<script src="/jsBundles/main.bundle.js"></script>
</body>
</html>
app.js
require(['./modules/someFunctions'],function(){
window.onload = function(){
var someFunctions = require('./modules/someFunctions');
document.getElementById('doubleIt').onclick = function(){
var num = document.getElementById('num').value;
document.getElementById('theCount').innerHTML = someFunctions.Double(num);
};
document.getElementById('tripleIt').onclick = function(){
var num = document.getElementById('num').value;
document.getElementById('theCount').innerHTML = someFunctions.Triple(num);
};
};
});
misc.js
var self = {};
self.isNumber = function(value){
// http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
return !isNaN(parseFloat(value)) && isFinite(value);
};
module.exports = self;
someFunctions.js
require(['./misc'], function(){
var misc= require('./misc');
var self = {};
self.Double = function(value){
if(!misc.isNumber(value)){
return 0;
};
return value*2;
}
self.Triple = function(value){
if(!misc.isNumber(value)){
return 0;
};
return value*3;
}
module.exports = self;
});
노트
의존성을 설치하려면 npm i --save-dev 를 실행하십시오.
종속성이 설치되면 \ node_modules \ webpack \ bin \ webpack.js 노드를 실행 하십시오.
노드 webserver.js 를 실행하여 서버를 시작하십시오.