introdução básica
documentos de importação
// a.js
require('./b.js')
require('style-loader!css-loader!./a.css')
arquivo compactado
// cli
webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader!'
visualização html
// html
<script src='./a.bundle.js'></script>
Webpack选项Parâmetros
--watch
--progress
--display-modules
--display-razões
--color
--display-error-detalhes
configuração básica
Criar um projeto
mkdir Webpack Demo-
cd-demo Webpack
npm init
npm instalar Webpack --save-dev
mkdir src
mkdir dist
o VSC // VSCode
criar HTML e bundle.js introduzidas
criar webpack.config.js // consulte a API de configuração de rede oficial
//模块化输出
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
//
entrada detalhada e de saída
entrada de três tipos: cordas individuais, arranjos, o objeto
erradicar saída diferem entrada
[] matriz
feixe principal e sub-principal empacotado em
module.exports={
entry:[
'./src/script/main.js',
'./src/script/sub-main.js'
],
output:{
path:'./dist/js',
filename:'bundle.js'
},
}
[Objeto] - multi-página do aplicativo
principal e embalado em um pacote
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
Ação: a introdução de sincronização 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>
Este artigo é reproduzido em: macaco 2048➽ https://www.mk2048.com/blog/blog.php?id=hhabb0icbjb