注意:
本文假設你有webpack2 的基礎認識。
本文的目的是分離第三方代碼和自身代碼
項目結構如下所示:
61498117491_.pic.jpg
開始實戰(zhàn)
創(chuàng)建一個目錄<code>webpack-demo2</code>,并安裝<code>wbepack</code>械馆。
mkdir webpack-demo2 && cd webpack-demo2
npm init -y
npm install --save-dev webpack
安裝<code>jquery</code>
npm install jquery --save
安裝<code>html-webpack-plugin</code>
npm install html-webpack-plugin --save-dev
新建<code>index.html</code>文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack</title>
</head>
<body>
</body>
</html>
新建<code>index.js</code>文件
const $ = require('jquery');
$('body').html('hello world').css('color','red');
新建<code>webpack.config.js</code>文件
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './index.js',
vendor: 'jquery'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack
.optimize
.CommonsChunkPlugin({
name: ['vendor']
}),
new HtmlWebpackPlugin({
filename:'index.html',
template:'index.html',
inject:'body'
})
]
}
說明
上述代碼使用了多個入口封豪。
webpack.optimize.CommonsChunkPlugin 插件嫂侍,是一個可選的用于建立一個獨立文件(又稱作 chunk)的功能熙揍,這個文件包括多個入口 chunk 的公共模塊订咸。通過將公共模塊拆出來,最終合成的文件能夠在最開始的時候加載一次盟榴,便存起來到緩存中供后續(xù)使用曹质。
HtmlWebpackPlugin該插件將所有生成的js文件自動引入index.html中。當文件名帶有hash值時擎场,這個插件尤其有用羽德。
HtmlWebpackPlugin會根據(jù)模版生成一個新的html文件。
最后打包代碼:
webpack --config webpack.config.js
71498118152_.pic_hd.jpg
在瀏覽器中打開dist文件夾下的index.html就能看到效果了迅办。