webpack可以看做是模块打包机:它做的事情是,分析你的项目结构,找到JavaScript模块以及其它的一些浏览器不能直接运行的拓展语言(Scss,TypeScript等),并将其打包为合适的格式以供浏览器使用。
此文中举例项目的结构:
app.js是一个入口文件,它去获取各个模块文件module.js(和index.css),然后通过webpack来打包编译成项目文件compiled.js,最后index.html直接去调用此项目文件compiled.js的代码获得理想的页面。
1.全局安装webpack
电脑要先装好node和npm,直接node.js官网下载
打开命令提示符(电脑左下角搜cmd)输入node -v和npm -v获得版本号
接下来全局安装webpack,
npm i -g webpack
在cmd输入webpack -v获得版本号
新建一个文件夹webpack_demo作为webpack的根目录,在cmd进入该文件夹并初始化
C:\Users\luo>d:
D:\>cd Desktop\webpack_demo
D:\Desktop\webpack_demo>npm init//初始化
输入信息直接回车默认就好了
初始化后根目录会得到package.json。
2.文档建立
在此根目录新建文件夹src,src里面新建文档app.js(入口文件)和module.js(模块文件),内容如下:
//app.js
import log from "./module.js"
document.write("app was loaded!")
log()
//module.js
export default function(){
document.write("module has been loaded!")
}
在根目录新建文档index.html和webpack.config.js
<!--index.html-->
<!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>Document</title>
<script src="dist/compiled.js"></script>
</head>
<body>
</body>
</html>
//webpack.config.js
const path = require("path")
module.exports= {
entry: "./src/app.js",
output:{
path: path.join(__dirname,"dist"),
filename: "compiled.js"
},
mode: "development"
}
新建之后项目目录:
3.运行
接着安装 webpack-cli(此工具用于在命令行中运行 webpack)
npm install webpack webpack-cli --save-dev
在cmd运行
D:\Desktop\webpack_demo>webpack
运行成功之后自动建了新文件dist,里面有一个compiled.js文档,直接打开index.html页面有结果输出
4.css样式加载
src文件夹里新建index.css
body{
padding: 200px;
text-align: center;
color: white;
background-color: #666
}
然后在app.js中插入:
import './index.css'
在webpack.config.js中加上:
const path = require("path")
module.exports= {
entry: "./src/app.js",
output:{
path: path.join(__dirname,"dist"),
filename: "compiled.js"
},
mode: "development" ,
module:{
rules: [
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
}
}
在cmd下载webpack载入器loader:
npm i css-loader
npm i style-loader
然后cmd运行webpack,打开index.html结果:
5.关于配置文件中的entry和ouput
- 一个入口文件main.js
- 一个数组:
entry: ["./src/script/main.js","./src/script/a.js"]
两个不相干入口文件打包进同一个bundle.js - 一个对象:
entry: { main: "./src/script/main.js", a: "./src/script/a.js" }
(两个chunk)output的filename不能写死成bundle.js会报错,必须用output的占位符:[name](entry对象的key)、[hash](这次打包的hash)、[chunkhash](chunk的hash或者打包文件的hush),比如[name].js,就会生成两个打包文件
6.自动生成html页面(设定 HtmlWebpackPlugin)
安装插件:
npm install --save-dev html-webpack-plugin
更改webpack.config.js:
const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: "./src/script/main.js",
a: "./src/script/a.js"
},
+ plugins: [
+ new HtmlWebpackPlugin({
+ title: 'Output Management'
+ })
+ ],
output: {
filename: "[name]-[hash].bundle.js",
path: path.resolve(__dirname, 'dist')
}
};
运行webpack会产生index.html,该文件会引用main和a的两个打包文件
7.以根目录index.html为模板在dist产生需要的html文件
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: "./src/script/main.js",
a: "./src/script/a.js"
},
output: {
path: path.resolve(__dirname,"dist"),//路径
filename: "js/[name].bundle.js",
//打包文件存放路径
//output的占位符:
//[name](entry对象的key)、
//[hash](这次打包的hash)、
//[chunkhash](chunk的hash或者打包文件的hush)
+ publicPath: 'http://cdn.com//'//上线用
},
plugins: [
new HtmlWebpackPlugin({
+ filename: 'index.html',//创建的文件名
+ title: 'Output Management',//html文件里的title
+ template: 'index.html',//模板
+ inject: false,//默认body,'head'引用打包文件script放在head里
+ date: new Date(),//日期
+ minify: {
removeComments: true,//去掉注释
collapseWhitespace: true,//去掉空格
}
})
],
mode: "development"
}
根目录下index.html模板文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
<script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
</head>
<body>
<!-- 加等号直接取值,没等号运行js代码 -->
<%= htmlWebpackPlugin.options.date %>
<script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks.a.entry %>"></script>
</body>
</html>
运行webpack结果在.dist/里产生index.html文件:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Output Management</title><script type="text/javascript" src="http://cdn.com//js/main.bundle.js"></script></head><body>Wed Jan 09 2019 23:03:11 GMT+0800 (中国标准时间)<script type="text/javascript" src="http://cdn.com//js/a.bundle.js"></script></body></html>
8.用htmlwebpackplugin同时创建多个html页面
通过设置多个不同new HtmlWebpackPlugin同时创建不同html文件
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: "./src/script/main.js",
a: "./src/script/a.js",
+ b: "./src/script/b.js"
},
output: {
path: path.resolve(__dirname,"dist"),//路径
filename: "js/[name].bundle.js",
//打包文件存放路径
//output的占位符:
//[name](entry对象的key)、
//[hash](这次打包的hash)、
//[chunkhash](chunk的hash或者打包文件的hush)
publicPath: 'http://cdn.com//'//上线用
},
plugins: [
new HtmlWebpackPlugin({
+ filename: 'main.html',//创建的文件名,路径和output里的path保持一致
+ title: 'Output main',//html文件里的title
template: 'index.html',//模板
inject: false,//默认body,'head'引用打包文件script放在head里
date: new Date(),//日期
+ chunk: ['main','a'],//打包后html文件可以调用的chunks
+ excludeChunks: ['b']//排除这个chunks
}),
new HtmlWebpackPlugin({
+ filename: 'a.html',//创建的文件名
+ title: 'Output a',//html文件里的title
template: 'index.html',//模板
inject: false,//默认body,'head'引用打包文件script放在head里
date: new Date(),//日期
}),
new HtmlWebpackPlugin({
+ filename: 'b.html',//创建的文件名
+ title: 'Output b',//html文件里的title
template: 'index.html',//模板
inject: false,//默认body,'head'引用打包文件script放在head里
date: new Date(),//日期
})
],
mode: "development"
}
9.热加载
安装webpack dev sever:
npm install webpack-dev-server --g
webpack.config.js增加:
module.exports = {
...
devServer: {
contentBase: path.resolve(__dirname, './dist'),
host: 'localhost',
compress: true,
port: 8888,
historyApiFallback: true,
}
...
}
运行webpack-dev-server
得到服务端localhost:8888,默认路径为./dist,打开dist里的app.html或者module.js,然后更改src里的文件,保存后会自动更新打包并加载新页面。
last.
Cannot find module ‘webpack/lib/node/NodeTemplatePlugin’
解决方法:
1,可以在本项目中安装,npm install webpack
2, npm link webpack --save-dev
D:\wamp64\www\webpack_demo>npm link webpack --save-dev
D:\wamp64\www\webpack_demo\node_modules\webpack ->C:\Users\luo\AppData\Roaming\npm\node_modules\webpack