首先要cd到自己的项目目录下,然后使用npm创建项目
npm init
编写自己的js文件
webpack you.js bundle.js
这样就能成功的打包了
在命令行中使用webpack要指定module时可以使用以下方法
webpack you.js bundle.js --module-bind the_modelu_name
简单的介绍几个常用的module
- ’css=style-loader!css-loader’
- 察看打包过程 –progress
- 察看打包模块详情 –display-modele
- 察看打包模块原因 –display-reason
webpack 的基础配置
最简单的配置
module.exports = {
entry:'you/own/main.js',
output:{
path:'the/path/you/want/to/save',
filename:'theOutputFileName.js'
}
}
如果我们直接用webpack.config.js进行webpack打包,那么我们想要使用之前在命令行中使用的模块,那么我们应该打开项目根目录下由npm init目录创建的package.json文件
基本内容如下:
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
我们要在scripts中写入要执行的命令:
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack":"webpack --progress --display-module --colors --display-reason"
},
"author": "",
"license": "ISC"
}
entry的配置
entry有三种配置方式
单文件模式
entry:'the/js/path.js'
主要用于单文件打js打包
数组模式
entry:['the/js/path1.js','the/js/path2.js']
主要用于解决两个平级的,互相依赖的文件打包到一起
对象模式
entry:{ pageOne:'the/js/path.js', pageTwo:['the/js/path1.js','the/js/path2.js'] }
用于多个页面的js打包
output的配置
output:{
path:'the/paht/you/want/to/save',
filename:[name]-[crunkhash].js
}
其中[name],[chunkhash],[hash]是占位符
- [name]用来表示文件名
- [chunkhash]表示本文件的md5 hash值
- [hash]用来表示本次打包的md5 hash值
实际html中的使用
为了保证文件的唯一性问题,我们通常要使用crunkhash来每次生成不同的文件,但是我们不可能每次都手工修改在html中的js引用文件名,所以这个时候我们就要借用相关插件了
npm install -g html-webpack-plugin
htmlwebpackplugin插件的使用方法
##### 单个html文件
在webpack.config.js中
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:{
main:'./main.js',
index:'./index.js',
this:'./this.js'
},
output:{
path:'./the/output/',
filename:'[name]-[chunkhash].js
},
plugins:[
new htmlWebpackPlugin{(
filename:'theFileNameAsYouLike-[hash].html',
//指定文件名,也可以不指定
template:'./index.html',
//打包文件的模版及位置,也就是原html文件
inject:'body',
//script放置位置,建议使用body
publicPaht:'http://youURL/'
//线上地址的URL,这样打包之后所有的文件内容都会改成线上地址
minify:{ //对html进行压缩
removeComments:true,
//删除注释
collapseWhitespace:true,
//删除空格
},
chunk:['main','index'],
//允许你只加载自己需要的js,这里的main,index就是指在entry中指定的main,index这个属性多用于在多文件中
excludeChunk['this'],
//加载在entry中除了this外所有的js文件.一般与chunk属性只使用其中的某一个
)]
}
这样执行webpack命令就可以执行打包,并自动引用最新的js文件
多个html文件
在webpack.config.js中
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:{
main:'./main.js',
index:'./index.js'
},
output:{
path:'./the/output/',
filename:'the/path/you/want/save/[name]-[chunkhash].js
},
//因为plugins对象的值是数组,所以我们可以写多个值,对于多个页面,直接进行多次构建即可
plugins:[
new htmlWebpackPlugin({
filename:'the/path/you/want/save/theFileNameAsYouLike-[hash].html',
template:'./pageOne.html',
}),
new htmlWebpackPlugini({
filename:'the/path/you/want/save/theFileNameAsYouLike2-[hash].html',
template:'./pageTwo.html',
})
]
}