basic introduction
Import documents
// a.js
require('./b.js')
require('style-loader!css-loader!./a.css')
Packed file
// cli
webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader!'
Preview html
// html
<script src='./a.bundle.js'></script>
webpack选项参数
--watch
--progress
--display-modules
--display-reasons
--color
--display-error-details
basic configuration
Create a project
mkdir WebPACK Demo-
cd-Demo WebPACK
npm the init
npm install WebPACK --save-dev
mkdir src
mkdir dist
the VSC // VSCode
create html and introduced bundle.js
create webpack.config.js // refer to the official network configuration API
//模块化输出
module.exports={
//
entry:'./src/script/main.js',
output:{
path:'./dist/js',
filename:'bundle.js'
},
}
//cli
webpack --config webpack.dev.config.js//指定config文件为webpack.dev.config.js
//
Detailed entry and output
entry three types: single strings, arrays, the object
output eradicate differ entry
[] array
main and sub-main bundle packaged into
module.exports={
entry:[
'./src/script/main.js',
'./src/script/sub-main.js'
],
output:{
path:'./dist/js',
filename:'bundle.js'
},
}
[Object] - multi-page application
main and packaged into a bundle
module.exports={
entry:{
page1:'./src/script/main.js',
page2:[
'./src/script/main.js',
'./src/script/sub-main.js'
],
},
output:{
path:'./dist/js',
//【占位符】hash本次 chunkhash静态资源改变后才变化
filename:'[name]-[hash]-[chunkhash].js'
},
}
Use plug-ins
html-wabpack-plugin
Action: the introduction of synchronization html js chunkhash
//cli
npm install html-wabpack-plugin --save-dev
//webpack.config.js
var htmlWebpackPlugin=require('html-wabpack-plugin')
module.exports={
// 上下文的默认环境就是当前运行脚本的目录
// context:
entry:{
page1:'./src/script/main.js',
page2:[
'./src/script/main.js',
'./src/script/sub-main.js'
],
},
output:{
path:'./dist',
// js
filename:'js/[name]-[hash]-[chunkhash].js',
// 上线环境的
publicPath:'http://m.mi.com/'
},
// 所有plugin都输出到output.path
plugin:[
//初始化插件 并传入相关参数
new htmlWebpackPlugin({
// 上下文环境 以根目录html作为模板
template:'index.html',
filename:'index-[hash].html',
inject:'head',//不配置的话 默认放到body标签内
//向html里面传参,
//在html用<%= htmlWebpackPlugin.options.title %>接收
title:'haha',//date:new Date(),
//压缩html 删除注释和空格
minify:{
removeComments:true,
collapseWhitespace:true
}
});
]
}
<!-- index.html -->
<!-- 可以编写js的模板引擎<%= 赋值 %><% 执行 %> -->
<% for (var key in htmlWebpackPlugin.files) {%>
<%= key %> : <%= JSON.stringify(htmlWebpackPlugin.files[key]) %>
<% } %>
<% for (var key in htmlWebpackPlugin.options) {%>
<%= key %> : <%= JSON.stringify(htmlWebpackPlugin.files[key]) %>
<% } %>
<!-- 用处 -->
<script src="<%= htmlWebpackPlugin.files.chunks.main.entry%>"></script>
This article is reproduced in: ape 2048➽ https://www.mk2048.com/blog/blog.php?id=hhabb0icbjb