本文用到的版本是 webpack v1

安装

全局

1
sudo npm install webpack -g

当前项目

1
2
npm install webpack@1.14.x --save
node_modules/.bin/webpack entry.js bundle.js

查看版本信息

1
npm info webpack

安装指定版本

1
sudo npm install webpack@1.14.x -g

卸载

1
2
卸载全局安装模块
npm uninstall -g webpack

使用

由于现在webpack出了2版本,简单起见我都是项目本地方式运行

1
node_modules/.bin/webpack ...

初始项目目录

1
npm init

打包文件 bundle.js

  • 文件 index.html
1
2
3
4
5
6
7
8
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <script src="bundle.js"></script>
</body>
</html>
  • 文件 entry.js
1
document.write('It works.')
  • 编译
1
node_modules/.bin/webpack ./entry.js bundle.js

require模块引用

  • 新建 content.js
1
module.exports = "It works from content.js.";
  • 修改 entry.js
1
+ document.write(require("./content.js"));
  • 编译
1
node_modules/.bin/webpack ./entry.js bundle.js

编译 css

  • 安装插件
1
npm install css-loader style-loader --save
  • 添加 style.css
1
2
3
body {
    background: yellow;
}
  • 修改 entry.js
1
2
require("!style!css!./style.css");
document.write(require("./content.js"));
  • 编译
1
node_modules/.bin/webpack ./entry.js bundle.js

简化 css 页面标签

  • 修改 entry.js
1
2
require("./style.css");
document.write(require("./content.js"));
  • 编译
1
node_modules/.bin/webpack ./entry.js bundle.js --module-bind 'css=style!css'

加入了参数 –module-bind “css=style!css”

使用配置文件

  • 添加 webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" }
        ]
    }
};
  • 编译
1
node_modules/.bin/webpack

编译时显示彩色和进度

1
node_modules/.bin/webpack --progress --colors

监控模式

1
node_modules/.bin/webpack --watch

本地开始一个express server 方便调试

  • 安装
1
2
3
sudo npm install webpack-dev-server -g
or
npm install webpack-dev-server@1.x --save
  • 运行
1
2
3
webpack-dev-server --progress --colors
or
node_modules/.bin/webpack-dev-server --progress --colors

http://localhost:8080

打印错误信息

1
node_modules/.bin/webpack --display-error-details

文档

http://webpack.github.io/docs/usage.html