+0
日增长
9,558
stars
2,208
forks
399
watchers
37
prs
65
issues
0
releases
README
This repo is a collection of simple demos of Webpack.
These demos are purposely written in a simple and clear style. You will find no difficulty in following them to learn the powerful tool.
How to use
First, install Webpack and webpack-dev-server globally.
bash
$ npm i -g webpack webpack-dev-server
Then, clone the repo.
bash
$ git clone https://github.com/ruanyf/webpack-demos.git
Install the dependencies.
bash
$ cd webpack-demos
$ npm install
Now, play with the source files under the repo's demo directories.
bash
$ cd demo01
$ npm run dev
If the above command doesn't open your browser automatically, you have to visit http://127.0.0.1:8080 by yourself.
Foreword: What is Webpack
Webpack is a front-end tool to build JavaScript module scripts for browsers.
It can be used similar to Browserify, and do much more.
bash
$ browserify main.js bundle.js
be equivalent to
$ webpack main.js bundle.js
Webpack needs a configuration file called webpack.config.js which is just a CommonJS module.
javascript
// webpack.config.js
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js'
}
};
After having webpack.config.js, you can invoke Webpack without any arguments.
bash
$ webpack
Some command-line options you should know.
- webpack – building for development
- webpack -p – building for production (minification)
- webpack --watch – for continuous incremental building
- webpack -d – including source maps
- webpack --colors – making building output pretty
You could customize scripts field in your package.json file as following.
javascript
// package.json
{
// ...
"scripts": {
"dev": "webpack-dev-server --devtool eval --progress --colors",
"deploy": "NODE_ENV=production webpack -p"
},
// ...
}
Index
1. Entry file
1. Multiple entry files
1. Babel-loader
1. CSS-loader
1. Image loader
1. CSS Module
1. UglifyJs Plugin
1. HTML Webpack Plugin and Open Browser Webpack Plugin
1. Environment flags
1. Code splitting
1. Code splitting with bundle-loader
1. Common chunk
1. Vendor chunk
1. Exposing Global Variables
1. React router
Demo01: Entry file (source)
Entry file is a file which Webpack reads to build bundle.js.
For example, main.js is an entry file.
javascript
// main.js
document.write('Hello World');
index.html
html
Webpack follows webpack.config.js to build bundle.js.
javascript
// webpack.config.js
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js'
}
};
Launch the server, visit http://127.0.0.1:8080 .
bash
$ cd demo01
$ npm run dev
Demo02: Multiple entry files (source)
Multiple entry files are allowed. It is useful for a multi-page app which has different entry file for each page.
javascript
// main1.js
document.write('Hello World');
// main2.js
document.write('Hello Webpack');
index.html
html
webpack.config.js
javascript
module.exports = {
entry: {
bundle1: './main1.js',
bundle2: './main2.js'
},