introducción básica
Los documentos de importación
// a.js
require('./b.js')
require('style-loader!css-loader!./a.css')
archivo embalado
// cli
webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader!'
Vista previa hTML
// html
<script src='./a.bundle.js'></script>
WebPack选项Lista de parámetros
--watch
--progress
--display-módulos
--display razones-
--color
--display-error-detalles
La configuración básica
Crear un proyecto
mkdir webpack Demo-
CD-Demo webpack
NPM el init
NPM instalar webpack --save-dev
mkdir src
mkdir dist
del VSC // VSCode
crear HTML y bundle.js introducidas
crear webpack.config.js // refieren a la API de configuración de la red 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 detallada y de salida
de entrada de tres tipos: cuerdas sueltas, matrices, el objeto
erradicar salida difieren entrada
[] array
haz principal y sub-principal empaquetado en
module.exports={
entry:[
'./src/script/main.js',
'./src/script/sub-main.js'
],
output:{
path:'./dist/js',
filename:'bundle.js'
},
}
[Objeto] - multi-página de la aplicación
principal y empaquetado en un paquete
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'
},
}
Usar plug-ins
html-wabpack-plugin
Acción: la introducción de sincronización 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 artículo se reproduce en: mono 2048➽ https://www.mk2048.com/blog/blog.php?id=hhabb0icbjb