全局安装
$ npm install -g webpack
查看版本
$ webpack -v
3.8.1
不过官方建议在本地安装,不要全局安装
本地安装
-
首先在文件夹初始化npm,生成
package.json
文件-
npm init
后可以直接回车,后期可改$ npm init ... Press ^C at any time to quit. package name: (webpack3.x) webpack_test version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to write to E:\webpack3.x\package.json: { "name": "webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this ok? (yes) yes
-
npm init -y
-
-
本地安装
$ npm install --save-dev webpack > uglifyjs-webpack-plugin@0.4.6 postinstall E:\webpack3.x\node_modules\uglifyjs-webpack-plugin > node lib/post_install.js npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN webpack_test@1.0.0 No description npm WARN webpack_test@1.0.0 No repository field. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) + webpack@3.8.1 added 367 packages in 31.694s
-
--save
生产依赖,把webpack添加到package.json
文件的dependencies
里面 -
--save-dev
开发依赖,把webpack安装到开发环境中,添加到package.json
文件的devDependencies
里面
-
关于 dependencies(依赖包)
的区别:
-
peer-dependencies
同等的依赖包 -
bundled-dependencies
捆绑依赖包 -
develop-dependencies
开发依赖包 -
optional-dependencies
可选择的依赖包
先来个小demo
-
建立项目结构
-
目前存在的结构:
webpack3.x |- node_modules |- package.json
-
新建
webpack3.x |- dist # 生产环境文件夹 |- index.html # 因为是一个demo,所以在dist文件夹建一个html文件 |- node_modules |- src # 源代码文件夹 |- index.js # 入口文件 |- package.json
-
dist/index.html
内容<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="author" content="duminghong" /> <title>webpack3.x</title> </head> <body> <div id="demo"></div> <script type="text/javascript" src="./bundle.js"></script> </body> </html>
-
src/index.js
内容document.getElementById('demo').innerHTML = 'Hello Webpack';
-
-
开始打包
webpack <entry> <output>
$ webpack src/index.js dist/bundle.js Hash: 11d2e9b0f73cf5895c49 Version: webpack 3.8.1 Time: 52ms Asset Size Chunks Chunk Names bundle.js 2.54 kB 0 [emitted] main [0] ./src/index.js 66 bytes {0} [built]
打包完成之后,会发现
dist
文件夹下面会多出个bundle.js
文件
webpack.config.js
首先在项目根目录下创建 webpack.config.js
配置文件
配置文件 webpack.config.js
的基本结构:
module.exports={
entry: {}, // 入口配置项
output: {}, // 出口配置项
module: {}, // 模块配置项:例如解读CSS,图片如何转换,压缩
blugins: [], // 插件配置项:用于生产模版和各项功能
devServer: {}, // 服务配置项:配置webpack开发服务功能
}
配置入口和出口
const path = require('path'); // 引入node的path模块
module.exports={
entry: {
entry: './src/index.js' // 入口文件
},
output: {
path: path.resolve(__dirname, 'dist'), // 打包路劲(获取绝对路径)
filename: 'bundle.js' // 打包文件
},
module: {},
plugins: [],
devServer: {},
}
开始打包
$ webpack
Hash: 51f1a51889d2e9637dc1
Version: webpack 3.8.1
Time: 54ms
Asset Size Chunks Chunk Names
bundle.js 2.54 kB 0 [emitted] entry
[0] ./src/index.js 66 bytes {0} [built]
多出口多入口
在 src
下新建 index2.js
webpack3.x
|- dis
|- index.html
|- node_modules
|- src
|- index.js
|- index2.js # 新建 index2.js
|- package.json
|- webpack.config.js
index2.js
内容
document.getElementById('demo2').innerHTML = 'index2.js Webpack!!';
在 dist/index.html
里,相应的做出改变
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="author" content="duminghong" />
<title>webpack3.x</title>
</head>
<body>
<div id="demo"></div>
<div id="demo2"></div>
<script type="text/javascript" src="./index.js"></script>
<script type="text/javascript" src="./index2.js"></script>
</body>
</html>
webpack.config.js
配置
const path = require('path');
module.exports={
entry: {
index: './src/index.js', // 入口文件1
index2: './src/index2.js', // 入口文件2
},
output: {
path: path.resolve(__dirname, 'dist'), // 路径不变
filename: '[name].js' // 打包文件([name] 为entry中对应的键名)
},
module: {},
plugins: [],
devServer: {},
}
开始打包
$ webpack
Hash: 0541c15f6aedca814b45
Version: webpack 3.8.1
Time: 53ms
Asset Size Chunks Chunk Names
index2.js 2.55 kB 0 [emitted] index2
index.js 2.54 kB 1 [emitted] index
[0] ./src/index.js 66 bytes {1} [built]
[1] ./src/index2.js 66 bytes {0} [built]
服务
首先安装 webpack-dev-server
模块
$ npm install webpack-dev-server --save-dev
配置 webpack.config.js
服务项
devServer: {
contentBase: path.resolve(__dirname, 'dist'), // 基本目录结构(服务器根目录)
host: '192.168.31.230', // 服务器地址(可以使用IP也可以使用localhost,用ipconfig命令查看自己的IP)
port: 8080, // 端口
compress: true // 是否启用服务器压缩
},
现在执行 $ webpack-dev-server
会报错,因为 webpack-dev-server
是安装在本目录的node_modules
文件夹里的,不在环境变量中,终端是找不到的
在 package.json
中的 scripts
配置 webpack-dev-server
{
"name": "webpack_test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"server": "webpack-dev-server" // 配置别名server (注意:JSON文件不支持注释)
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
}
}
执行scripts配置的命令
$ npm run server
> webpack_test@1.0.0 server E:\webpack3.x
> webpack-dev-server
Project is running at http://192.168.31.230:8080/
webpack output is served from /
Content not from webpack is served from E:\webpack3.x\dist
Hash: 5cde9c67fc444d588f2d
Version: webpack 3.8.1
Time: 411ms
Asset Size Chunks Chunk Names
index2.js 324 kB 0 [emitted] [big] index2
index.js 324 kB 1 [emitted] [big] index
......
webpack: Compiled successfully.
webpack-dev-server
启动成功,并打包成功 (注意:webpack-dev-server
打包不会生成文件,只会在内存里),访问配置的域名http://192.168.31.230:8080/
就可以查看
热更新
webpack 3.6.0+
是直接支持热更新的,所以直接修改保存入口文件,会把你的所有修改同步更新到浏览器中
打包css
首先在 src
下新建 css/index.css
webpack3.x
|- dis
|- index.html
|- node_modules
|- src
|- css
|- index.css # 新建 index.css
|- index.js
|- index2.js
|- package.json
|- webpack.config.js
index.css
内容
body{
background-color: #ececec;
}
#demo{
color: red;
}
#demo2{
color: green;
}
在 index.js
里引入这个css文件,index.js
内容
import css from './css/index.css'
document.getElementById('demo').innerHTML = 'Hello Webpack';
准备好了之后,需要安装两个转换器 style-loader
css-loader
-
css-loader 用来将css插入到页面的style标签
$ npm install css-loader --save-dev
-
style-loader 用来处理css文件中的url()等
$ npm install style-loader --save-dev
在 webpack.config.js
模块配置项中配置 loaders
module:{
rules: [
{
test: /\.css$/, // 用正则找到需要处理的文件扩展名
use: [ 'style-loader', 'css-loader' ], // 需要使用的loader
/** use属性也可以换成loader
* loader: [ 'style-loader', 'css-loader' ],
*
* use 的值也可以是个对象
* use: [
* {loader: 'style-loader'},
* {loader: 'css-loader'}
* ],
*/
}
]
},
执行scripts配置的命令
$ npm run server
> webpack_test@1.0.0 server E:\webpack3.x
> webpack-dev-server
Project is running at http://192.168.31.230:8080/
......
webpack: Compiled successfully.
打包成功,打开浏览器访问配置的域名查看
打包压缩 JS
在 webpack.config.js
中引入webpack的压缩插件 uglify
,并在插件配置项里(plugins
)配置
const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');
module.exports={
entry: {
index: './src/index.js', // 入口文件1
index2: './src/index2.js', // 入口文件2
},
output: {
path: path.resolve(__dirname, 'dist'), // 路径不变
filename: '[name].js' // 打包文件([name] 为entry中对应的键名)
},
module:{
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new uglify()
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'), // 基本目录结构(服务器根目录)
host: '192.168.31.230', // 服务器地址(最好是自己电脑的ip地址,用ipconfig命令查看自己的ip)
port: 8080, // 端口
compress: true // 是否启用服务器压缩
},
}
执行打包
$ webpack
Hash: 5556a43b90b0ef0d4ab7
Version: webpack 3.8.1
Time: 2175ms
Asset Size Chunks Chunk Names
index.js 6.45 kB 0 [emitted] index
index2.js 549 bytes 1 [emitted] index2
[0] ./src/index.js 96 bytes {0} [built]
[1] ./src/css/index.css 1.1 kB {0} [built]
[2] ./node_modules/_css-loader@0.28.7@css-loader!./src/css/index.css 294 byte
s {0} [built]
[6] ./src/index2.js 73 bytes {1} [built]
+ 3 hidden modules
然后再查看打包之后的js,就压缩了
打包html
重新调整目录如下
webpack3.x
|- dis
|- node_modules
|- src
|- css
|- index.css
|- index.js
|- index.html
|- package.json
|- webpack.config.js
-
把dist目录清空
-
新增
index.html
,内容如下<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="author" content="duminghong" /> <title>webpack3.x</title> </head> <body> <div id="demo"></div> </body> </html>
安装html压缩插件
$ npm install --save-dev html-webpack-plugin
在 webpack.config.js
中引入webpack的html压缩插件,并在插件配置项里(plugins
)配置
const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');
const htmlPlugin = require('html-webpack-plugin');
module.exports={
entry: {
index: './src/index.js' // 入口文件
},
output: {
path: path.resolve(__dirname, 'dist'), // 路径不变
filename: '[name].js' // 打包文件([name] 为entry中对应的键名)
},
module:{
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new uglify(),
new htmlPlugin({
// 压缩配置
minify: {
removeAttributeQuotes: true // 去掉标签上属性的引号
},
hash: true, // 加hash (不让浏览器缓存)
template: './src/index.html' // 打包模版
})
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'), // 基本目录结构(服务器根目录)
host: '192.168.31.230', // 服务器地址(最好是自己电脑的ip地址,用ipconfig命令查看自己的ip)
port: 8080, // 端口
compress: true // 是否启用服务器压缩
},
}
执行打包
$ webpack
Hash: 9bca49293edabcad57dc
Version: webpack 3.8.1
Time: 2353ms
Asset Size Chunks Chunk Names
index.js 6.45 kB 0 [emitted] index
index.html 313 bytes [emitted]
[0] ./src/index.js 96 bytes {0} [built]
[1] ./src/css/index.css 1.1 kB {0} [built]
[2] ./node_modules/_css-loader@0.28.7@css-loader!./src/css/index.css 294 byte
s {0} [built]
+ 3 hidden modules
Child html-webpack-plugin for "index.html":
1 asset
[0] ./node_modules/_html-webpack-plugin@2.30.1@html-webpack-plugin/lib/lo
ader.js!./src/index.html 650 bytes {0} [built]
[2] (webpack)/buildin/global.js 488 bytes {0} [built]
[3] (webpack)/buildin/module.js 495 bytes {0} [built]
+ 1 hidden module
打包成功之后查看dist目录,出现打包之后的两个文件index.html
、index.js
,并且在index.html里已经自动引入了index.js
:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
<meta name=author content=duminghong>
<title>webpack3.x</title>
</head>
<body>
<div id=demo></div>
<script type=text/javascript src=index.js?9bca49293edabcad57dc></script></body>
</html>
css中引入图片
新增img文件夹,重新调整目录如下
webpack3.x
|- dis
|- node_modules
|- src
|- css
|- index.css
|- img
|- pic.jpg
|- index.js
|- index.html
|- package.json
|- webpack.config.js
修改index.css
内容
body{
background-color: #ececec;
}
#demo{
width: 750px;
height: 420px;
background: url(../img/pic.jpg) no-repeat;
}
安装 file-loader
和 url-loader
$ npm install --save-dev file-loader url-loader
在 webpack.config.js
模块配置项中配置 loaders
module:{
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: {
limit: 10000 // 小于10000个字节的图片转为base64
}
}]
}
]
},
执行打包
$ webpack
Hash: 7ab61639f456a5b2e95d
Version: webpack 3.10.0
Time: 1582ms
Asset Size Chunks Chunk Names
de384cbb7e1df0d41d72795a9391bc8f.jpg 160 kB [emitted]
index.js 6.58 kB 0 [emitted] index
index.html 313 bytes [emitted]
[0] ./src/index.js 96 bytes {0} [built]
[1] ./src/css/index.css 1.02 kB {0} [built]
[2] ./node_modules/css-loader!./src/css/index.css 329 bytes {0} [built]
[4] ./src/img/pic.jpg 82 bytes {0} [built]
+ 3 hidden modules
Child html-webpack-plugin for "index.html":
1 asset
[0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 635 bytes {0} [built]
[2] (webpack)/buildin/global.js 509 bytes {0} [built]
[3] (webpack)/buildin/module.js 517 bytes {0} [built]
+ 1 hidden module
打包成功之后查看dist目录,因为图片大于10000B,所以复制到dis目录了
|- css
|- de384cbb7e1df0d41d72795a9391bc8f.jpg
|- index.html
|- index.js
网友评论