Webpack 是个好东西,用的好可以构建一个很舒服的开发环境,让你可以潜心于业务逻辑,要是开发环境没有搭建好,换来的是开发过程中无尽的痛苦。下面就练习16个 Webapck 的 demo,几乎已经涵盖了 Webpack 的主要实用功能。
教程原地址:https://github.com/ruanyf/webpack-demos
Demo文件下载地址:ringcrl.com/web/sources/webpack-demo/webpack-demo.zip
运行demo前需在在 webpack-demo 目录下运行安装相关的依赖

  1. npm install

练习之前首先在本机全局安装 webpack 和 webpack-dev-server

  1. npm i -g webpack webpack-dev-server

webpack用来打包出实际的文件,webpack-dev-server用来生成一个缓存中的打包文件,并监听文件的变化,开发时体验十分良好。
webpack的配置文件是webpack.config.js,有了它就可以不带参数的使用webpack

  1. module.exports = {
  2. entry: './main.js',
  3. output: {
  4. filename: 'bundle.js'
  5. }
  6. };
  7. js

一些命令行的配置项

  • webpack – 构建文件
  • webpack -p – 发布
  • webpack --watch – 监听项目
  • webpack -d – 包含 source maps方便调试
  • webpack --colors – 让打包界面更好看

将命令行写入package.json

  1. {
  2. // ...
  3. "scripts": {
  4. "dev": "webpack-dev-server --devtool eval --progress --colors",
  5. "deploy": "NODE_ENV=production webpack -p"
  6. },
  7. // ...
  8. }

01单文件入口

webpack会将入口文件打包成bundle.js
webpack.config.js

  1. module.exports = {
  2. entry: './main.js',
  3. output: {
  4. filename: 'bundle.js'
  5. }
  6. };
  7. js

index.html

  1. <html>
  2. <body>
  3. <script type="text/javascript" src="bundle.js"></script>
  4. </body>
  5. </html>
  6. html

main.js

  1. document.write('<h1>Hello World</h1>');

02多文件入口

webpack.config.js

  1. module.exports = {
  2. entry: {
  3. bundle1: './main1.js',
  4. bundle2: './main2.js'
  5. },
  6. output: {
  7. filename: '[name].js'
  8. }
  9. };
  10. js

index.html

  1. <html>
  2. <body>
  3. <script src="bundle1.js"></script>
  4. <script src="bundle2.js"></script>
  5. </body>
  6. </html>
  7. html

main.js

  1. // main1.js
  2. document.write('<h1>Hello World</h1>');
  3. // main2.js
  4. document.write('<h2>Hello Webpack</h2>');
  5. js

03Babel-loader

Babel其实是一个编译JavaScript的平台可以将 JSX/ES6 文件转换成浏览器可以识别的js文件
webpack.config.js

  1. // 直接在 loader 中写参数
  2. module.exports = {
  3. entry: './main.jsx',
  4. output: {
  5. filename: 'bundle.js'
  6. },
  7. module: {
  8. loaders:[
  9. {
  10. test: /\.js[x]?$/,
  11. exclude: /node_modules/,
  12. loader: 'babel-loader?presets[]=es2015&presets[]=react'
  13. },
  14. ]
  15. }
  16. };
  17. // 将参数写在 query 对象中
  18. module: {
  19. loaders: [
  20. {
  21. test: /\.jsx?$/,
  22. exclude: /node_modules/,
  23. loader: 'babel',
  24. query: {
  25. presets: ['es2015', 'react']
  26. }
  27. }
  28. ]
  29. }
  30. js

index.html

  1. <html>
  2. <body>
  3. <div id="wrapper"></div>
  4. <script src="bundle.js"></script>
  5. </body>
  6. </html>
  7. html

main.jsx

  1. const React = require('react');
  2. const ReactDOM = require('react-dom');
  3. ReactDOM.render(
  4. <h1>Hello, world!</h1>,
  5. document.querySelector('#wrapper')
  6. );
  7. js

04CSS-loader

Webpack 允许你在js文件中require CSS , 通过 CSS-loader来预处理css文件
webpack.config.js

  1. // 需要使用两种 loaders 来转换 CSS 文件。第一个是 CSS-loader 来读取CSS文件, 另外一个是Style-loader 是将 style 样式插入到 html 中。中间用!连接。
  2. module.exports = {
  3. entry: './main.js',
  4. output: {
  5. filename: 'bundle.js'
  6. },
  7. module: {
  8. loaders:[
  9. { test: /\.css$/, loader: 'style-loader!css-loader' },
  10. ]
  11. }
  12. };
  13. js

index.html

  1. <html>
  2. <head>
  3. <script type="text/javascript" src="bundle.js"></script>
  4. </head>
  5. <body>
  6. <h1>Hello World</h1>
  7. </body>
  8. </html>
  9. html

app.css

  1. body {
  2. background-color: blue;
  3. }

main.js

  1. require('./app.css');

05Image loader

Webpack 允许你在js文件中require图片 , 通过 url-loader和file-loader来预处理图片文件
webpack.config.js

  1. // img是文件夹名,name是打包源文件的名字hash是哈希值,ext是同一的后缀名
  2. // 打包出来小图片(小于10000)转换成base64,大图片变成img/big.4853ca6.png
  3. module.exports = {
  4. entry: './main.js',
  5. output: {
  6. filename: 'bundle.js'
  7. },
  8. module: {
  9. loaders: [{
  10. test: /\.(png|jpg)$/,
  11. loader: 'url-loader',
  12. query: {
  13. limit: 10000,
  14. name:'img/[name].[hash:7].[ext]'
  15. }
  16. }]
  17. }
  18. };
  19. js

index.html

  1. <html>
  2. <body>
  3. <script type="text/javascript" src="bundle.js"></script>
  4. </body>
  5. </html>
  6. html

main.js

  1. var img1 = document.createElement("img");
  2. img1.src = require("./small.png");
  3. document.body.appendChild(img1);
  4. var img2 = document.createElement("img");
  5. img2.src = require("./big.png");
  6. document.body.appendChild(img2);
  7. js

06CSS Module

CSS Module可以开启全局变量和局部变量,:global(…)表示全局变量,可以在全局中使用样式
webpack.config.js

  1. // css-loader?modules (the query parameter modules) enables the CSS Modules spec
  2. module.exports = {
  3. entry: './main.jsx',
  4. output: {
  5. filename: 'bundle.js'
  6. },
  7. module: {
  8. loaders:[
  9. {
  10. test: /\.js[x]?$/,
  11. exclude: /node_modules/,
  12. loader: 'babel-loader',
  13. query: {
  14. presets: ['es2015', 'react']
  15. }
  16. },
  17. {
  18. test: /\.css$/,
  19. loader: 'style-loader!css-loader?modules'
  20. }
  21. ]
  22. }
  23. };
  24. js

index.html

  1. <html>
  2. <body>
  3. <h1 class="h1">Hello World</h1>
  4. <h2 class="h2">Hello Webpack</h2>
  5. <div id="example"></div>
  6. <script src="./bundle.js"></script>
  7. </body>
  8. </html>
  9. html

app.css

  1. .h1 {
  2. color:red;
  3. }
  4. :global(.h2) {
  5. color: blue;
  6. }
  7. css

main.jsx

  1. var React = require('react');
  2. var ReactDOM = require('react-dom');
  3. var style = require('./app.css');
  4. ReactDOM.render(
  5. <div>
  6. <h1 className={style.h1}>Hello World</h1>
  7. <h2 className="h2">Hello Webpack</h2>
  8. </div>,
  9. document.getElementById('example')
  10. );
  11. js

07UglifyJs Plugin

Webpack 可以去掉本身附加的东西,优化代码 UglifyJs 插件会最小化 bundle.js 代码
webpack.config.js

  1. var webpack = require('webpack');
  2. var uglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
  3. module.exports = {
  4. entry: './main.js',
  5. output: {
  6. filename: 'bundle.js'
  7. },
  8. plugins: [
  9. new uglifyJsPlugin({
  10. compress: {
  11. warnings: false
  12. }
  13. })
  14. ]
  15. };
  16. js

index.html

  1. <html>
  2. <body>
  3. <script src="bundle.js"></script>
  4. </body>
  5. </html>
  6. html

main.js

  1. var longVariableName = 'Hello';
  2. longVariableName += ' World';
  3. document.write('<h1>' + longVariableName + '</h1>');

08HTML Webpack Plugin and Open Browser Webpack Plugin

html-webpack-plugin 创建 index.html ,open-browser-webpack-plugin 打开浏览器
不用手写index.html 也不用手动打开浏览器 Webpack 可以为你做这些事
webpack.config.js

  1. var HtmlwebpackPlugin = require('html-webpack-plugin');
  2. var OpenBrowserPlugin = require('open-browser-webpack-plugin');
  3. module.exports = {
  4. entry: './main.js',
  5. output: {
  6. filename: 'bundle.js'
  7. },
  8. plugins: [
  9. new HtmlwebpackPlugin({
  10. title: 'Webpack-demos',
  11. filename: 'index.html'
  12. }),
  13. new OpenBrowserPlugin({
  14. url: 'http://localhost:8080'
  15. })
  16. ]
  17. };
  18. js

main.js

  1. document.write('<h1>Hello World</h1>');

09设置环境变量

可以利用环境变量来控制特定代码的输出
webpack.config.js

  1. var webpack = require('webpack');
  2. var devFlagPlugin = new webpack.DefinePlugin({
  3. __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
  4. });
  5. module.exports = {
  6. entry: './main.js',
  7. output: {
  8. filename: 'bundle.js'
  9. },
  10. plugins: [devFlagPlugin]
  11. };
  12. js

bash

  1. # Linux & Mac
  2. $ env DEBUG=true webpack-dev-server

index.html

  1. <html>
  2. <body>
  3. <script src="bundle.js"></script>
  4. </body>
  5. </html>
  6. html

main.js

  1. document.write('<h1>Hello World</h1>');
  2. if (__DEV__) {
  3. document.write(new Date());
  4. }
  5. js

10Code splitting

在commonjs中有一个Modules/Async/A规范,里面定义了require.ensure语法。webpack实现了它,作用是可以在打包的时候进行代码分片,并异步加载分片后的代码。用法如下: require.ensure([], function(require){ var list = require(‘./list’); list.show(); }); 此时list.js会被打包成一个单独的chunk文件
Webpack 自己动管理依赖、输出文件和运行时打包,你不用在 index.html 和 webpack.config.js 中手动管理依赖
webpack.config.js

  1. module.exports = {
  2. entry: './main.js',
  3. output: {
  4. filename: 'bundle.js'
  5. }
  6. };
  7. js

index.html

  1. <html>
  2. <body>
  3. <script src="bundle.js"></script>
  4. </body>
  5. </html>
  6. html

需要用 require.ensure to 来定义一个分割的点
main.js

  1. require.ensure(['./a'], function(require) {
  2. var content = require('./a');
  3. document.open();
  4. document.write('<h1>' + content + '</h1>');
  5. document.close();
  6. });
  7. js

a.js

  1. module.exports = 'Hello World';

11通过bundle-loader进行代码分裂

改写上面的 main.js,就可以使用 bundle.loder 进行比较优雅的代码分割

  1. // Now a.js is requested, it will be bundled into another file
  2. var load = require('bundle-loader!./a.js');
  3. // To wait until a.js is available (and get the exports)
  4. // you need to async wait for it.
  5. load(function(file) {
  6. document.open();
  7. document.write('<h1>' + file + '</h1>');
  8. document.close();
  9. });
  10. js

12Common chunk

利用webpack.optimize.CommonsChunkPlugin,你可以共通的组件,代码块分离出来
webpack.config.js

  1. var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
  2. module.exports = {
  3. entry: {
  4. bundle1: './main1.jsx',
  5. bundle2: './main2.jsx'
  6. },
  7. output: {
  8. filename: '[name].js'
  9. },
  10. module: {
  11. loaders:[
  12. {
  13. test: /\.js[x]?$/,
  14. exclude: /node_modules/,
  15. loader: 'babel-loader',
  16. query: {
  17. presets: ['es2015', 'react']
  18. }
  19. },
  20. ]
  21. },
  22. plugins: [
  23. new CommonsChunkPlugin('init.js')
  24. ]
  25. }
  26. js

index.html

  1. <html>
  2. <body>
  3. <div id="a"></div>
  4. <div id="b"></div>
  5. <script src="init.js"></script>
  6. <script src="bundle1.js"></script>
  7. <script src="bundle2.js"></script>
  8. </body>
  9. </html>

main1.js

  1. var React = require('react');
  2. var ReactDOM = require('react-dom');
  3. ReactDOM.render(
  4. <h1>Hello World</h1>,
  5. document.getElementById('a')
  6. );
  7. js

main2.js

  1. var React = require('react');
  2. var ReactDOM = require('react-dom');
  3. ReactDOM.render(
  4. <h2>Hello Webpack</h2>,
  5. document.getElementById('b')
  6. );
  7. js

13Vendor chunk

利用webpack.optimize.CommonsChunkPlugin,你可以把第三方库抽离出来
webpack.config.js

  1. var webpack = require('webpack');
  2. module.exports = {
  3. entry: {
  4. app: './main.js',
  5. vendor: ['jquery'],
  6. },
  7. output: {
  8. filename: 'bundle.js'
  9. },
  10. plugins: [
  11. new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'vendor.js'),
  12. // 这段代码是用于全局不用 require 就可以直接使用 $
  13. new webpack.ProvidePlugin({
  14. $: "jquery",
  15. jQuery: "jquery",
  16. "window.jQuery": "jquery"
  17. })
  18. ]
  19. };
  20. js

index.html

  1. <html>
  2. <body>
  3. <h1></h1>
  4. <script src="vendor.js"></script>
  5. <script src="bundle.js"></script>
  6. </body>
  7. </html>
  8. html

main.js

  1. var $ = require('jquery');
  2. $('h1').text('Hello World');

14Exposing_global variables

如果你想引入一些全局变量, 但是不想被加载处理, 你可以在 webpack.config.js 使用 externals 模块 (官方文档). 有时我们希望我们通过script引入的库,如用CDN的方式引入的jquery,我们在使用时,依旧用require的方式来使用,但是却不希望webpack将它又编译进文件中。
我们可以把 data 暴露为一个全局对象
webpack.config.js

  1. module.exports = {
  2. entry: './main.jsx',
  3. output: {
  4. filename: 'bundle.js'
  5. },
  6. module: {
  7. loaders:[
  8. {
  9. test: /\.js[x]?$/,
  10. exclude: /node_modules/,
  11. loader: 'babel-loader',
  12. query: {
  13. presets: ['es2015', 'react']
  14. }
  15. },
  16. ]
  17. },
  18. externals: {
  19. // require('data') is external and available
  20. // on the global var data
  21. 'data': 'data'
  22. }
  23. };
  24. js

data.js

  1. var data = 'Hello World';

main.jsx

  1. // require data 作为模块化引入进来使用. 但是实际上是一个全局变量
  2. var data = require('data');
  3. var React = require('react');
  4. var ReactDOM = require('react-dom');
  5. ReactDOM.render(
  6. <h1>{data}</h1>,
  7. document.body
  8. );
  9. js

15热模块替换

Hot Module Replacement(HMR)可以改变文件而不需要页面刷新,通过webpack-dev-server可以使用2种方式来进行热模块替换。
1、在命令行中

  1. webpack-dev-server --hot --inline
  • —hot: 增加 HotModuleReplacementPlugin 然后切换服务模式到 hot mode
  • —inline:将 webpack-dev-server runtime 嵌入 bundle

2、配置webpack.config.js

  • 添加 new webpack.HotModuleReplacementPlugin() 到 plugins 模块
  • 添加 webpack/hot/dev-server 和 webpack-dev-server/client?http://localhost:8080 到 entry 模块

webpack.config.js

  1. var webpack = require('webpack');
  2. var path = require('path');
  3. module.exports = {
  4. entry: [
  5. 'webpack/hot/dev-server',
  6. 'webpack-dev-server/client?http://localhost:8080',
  7. './index.js'
  8. ],
  9. output: {
  10. filename: 'bundle.js',
  11. publicPath: '/static/'
  12. },
  13. plugins: [
  14. new webpack.HotModuleReplacementPlugin()
  15. ],
  16. module: {
  17. loaders: [{
  18. test: /\.jsx?$/,
  19. exclude: /node_modules/,
  20. loader: 'babel-loader',
  21. query: {
  22. presets: ['es2015', 'react']
  23. },
  24. include: path.join(__dirname, '.')
  25. }]
  26. }
  27. };
  28. js

index.html

  1. <html>
  2. <body>
  3. <div id='root'></div>
  4. <script src="/static/bundle.js"></script>
  5. </body>
  6. </html>
  7. html

index.js

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import App from './App';
  4. ReactDOM.render(<App />, document.getElementById('root'));
  5. js

App.js

  1. import React, { Component } from 'react';
  2. export default class App extends Component {
  3. render() {
  4. return (
  5. <h1>Hello World</h1>
  6. );
  7. }
  8. }
  9. js

16React router例子

利用webpack做的例子 React-router’s 官方例子
webpack.config.js

  1. module.exports = {
  2. entry: './index.js',
  3. output: {
  4. filename: 'bundle.js'
  5. },
  6. module: {
  7. loaders:[
  8. { test: /\.css$/, loader: 'style-loader!css-loader' },
  9. { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' },
  10. ]
  11. }
  12. };
  13. js

index.html

  1. <html>
  2. <body>
  3. <div id="app"></div>
  4. <script src="/bundle.js"></script>
  5. </body>
  6. </html>
  7. html

app.css

  1. header *{
  2. display: inline;
  3. margin: 1em;
  4. border-bottom: 1px solid black;
  5. }
  6. css

index.js

  1. import React from 'react';
  2. import { render } from 'react-dom';
  3. import { Router, Route, Link, IndexRoute, browserHistory } from 'react-router';
  4. require('./app.css');
  5. var App = React.createClass({
  6. render: function () {
  7. return (
  8. <div>
  9. <header>
  10. <ul>
  11. <li><Link to="/app">Dashboard</Link></li>
  12. <li><Link to="/inbox">Inbox</Link></li>
  13. <li><Link to="/calendar">Calendar</Link></li>
  14. </ul>
  15. Logged in as Jane
  16. </header>
  17. {this.props.children}
  18. </div>
  19. );
  20. }
  21. });
  22. var Dashboard = React.createClass({
  23. render: function () {
  24. return (
  25. <div>
  26. <p>Dashboard</p>
  27. </div>
  28. );
  29. }
  30. });
  31. var Inbox = React.createClass({
  32. render: function () {
  33. return (
  34. <div>
  35. <p>Inbox</p>
  36. </div>
  37. );
  38. }
  39. });
  40. var Calendar = React.createClass({
  41. render: function () {
  42. return (
  43. <div>
  44. <p>Calendar</p>
  45. </div>
  46. );
  47. }
  48. });
  49. render((
  50. <Router history={browserHistory}>
  51. <Route path="/" component={App}>
  52. <IndexRoute component={Dashboard}/>
  53. <Route path="app" component={Dashboard}/>
  54. <Route path="inbox" component={Inbox}/>
  55. <Route path="calendar" component={Calendar}/>
  56. <Route path="*" component={Dashboard}/>
  57. </Route>
  58. </Router>
  59. ), document.querySelector('#app'));