天天看點

webpack4.x深入了解

1.webpack4.x的安裝

  • 使用npm初始化 一個檔案夾
D:\webpack-tset>npm init
           

先全部預設選項

Press ^C at any time to quit. //随時按^C退出。
package name: (webpack-tset)
version: (1.0.0)
...

Is this ok? (yes)
           
  • 安裝webpack

webpack 4.x 後需要安裝webpack-cli ,請注意需要同步安裝在目前目錄

D:\webpack-tset>npm install webpack --save-dev //安裝webpack
D:\webpack-tset> npm install -g webpack-cli //全局安裝webpack-cli,(如果之前沒有安裝的話)
D:\webpack-tset> npm install --save-dev webpack-cli //同步到局部項目檔案夾下
           

2.使用webpack打包一個檔案

建立一個檔案

webpack4.x深入了解

打包這個檔案,格式:webpack 檔案名 -o 打包後檔案名:

D:\webpack-tset> webpack hello.js -o hello.bundle.js
           
  • 在要被打包的檔案中引入另一檔案
webpack4.x深入了解
webpack4.x深入了解

現在變成了兩個子產品

  • 在檔案中引入css檔案,并打包

打包前需要安裝css-loader

D:\webpack-tset> npm install css-loader style-loader --save-dev
           
webpack4.x深入了解
webpack4.x深入了解

執行打包指令:

webpack4.x深入了解

這時變成了三個子產品

3.在網頁中展示打包效果

建立一個index.html檔案,并引入打包後的檔案

webpack4.x深入了解

打包hello.js檔案

webpack4.x深入了解

打開index.html檔案

webpack4.x深入了解
webpack4.x深入了解

此時hello.js的函數先被執行,執行完成後style.css的樣式才生效

再看一下index.html檔案的結構

webpack4.x深入了解

style-loarder負責在html檔案中插入style标簽

  • 用指令行指定css-loader

首先删除在hello,js檔案中引入的css-loader

webpack4.x深入了解

執行指令:

D:\webpack-tset> webpack hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader'
           
webpack4.x深入了解
  • 檔案更新自動打包
D:\webpack-tset> webpack hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader' --watch
           
  • 檢視打包進度,打包子產品,打包原因
D:\webpack-tset> webpack hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader' --progress --display-modules --display-reasons
           

4.webpack配置檔案

webapck4.x之後,配置檔案path必須為絕對路徑

webpack4.x深入了解
D:\webpack-demo> webpack --mode development //打包成未壓縮模式
           
  • 指定配置檔案
D:\webpack-demo> webpack --config a.js //a.js為配置檔案
           
  • 自定義npm指令腳本

在package.json檔案的scripts的屬性裡自定義指令:

webpack4.x深入了解

此時自定義的指令會替代配置好的指令

D:\webpack-demo> npm run webpack
           
  • webpack配置的entry,output

在 webpack配置檔案中定義

entry

 屬性,來指定多個入口起點:

webpack4.x深入了解

執行自定義指令:

webpack4.x深入了解

此時打包成了兩個檔案,再看打包後的bundle.js檔案:

webpack4.x深入了解

在entry中定義多個chunk:

webpack4.x深入了解

這種方式适合多頁面應用,這是打包後的輸出檔案應該區分開來,進而避免打包覆寫,在輸出裡重新定義filename的屬性值:

可以使用name-chunkhash.js格式來區分打包後的檔案

webpack4.x深入了解

執行打包指令

webpack4.x深入了解

打包後生成了兩個不同名稱的檔案

webpack4.x深入了解

5.自動化生成項目中的html頁面

  • 安裝插件
npm install html-webpack-plugin --save-dev
           

安裝完成後在webpack配置檔案中建立對插件的引用

const htmlWebpckPlugin=require('html-webpack-plugin')
           

在plugins中初始化對應的模闆:

plugins:[
        new htmlWebpckPlugin({
            template:'index.html' //根目錄
        }), //初始化
    ]
           
  • 在模闆中引用配置參數

首先安裝html加載器html-loader:

npm i html-loader --save-dev
           

配置參數:

plugins:[
        new htmlWebpckPlugin({
            title:'webpack is good'
        }), //初始化
    ]
           

在模闆中引用:

<%= htmlWebpackPlugin.options.title%>
           

打包後可以看到title值已經取到

webpack4.x深入了解
  • ejs模闆文法
<body>
    <% for ( const key in htmlWebpackPlugin.files) { %>
     <%=key %>:<%=JSON.stringify(htmlWebpackPlugin.files[key])%>
     <%}%>
    </div>
           

打包後顯示結果為:

webpack4.x深入了解
  • 根據模闆引擎自定義引入的檔案
webpack4.x深入了解

打包後結果為:

webpack4.x深入了解
  • 設定一個上線的路徑

通過對publicPath占位符的設定:

webpack4.x深入了解

打包後引用的檔案路徑前會被publicPath來插入

webpack4.x深入了解

其他一些配置參數:

plugins:[
        new htmlWebpckPlugin({
            minify:{
                removeComments:true,//删除注釋
                collapseWhitespace:false,//删除空格 和壓縮打包的差別
            }
        }), //初始化
    ]
           

6.通過plugins生成多頁面html

  • 定義多個chunk,在plugins裡多次調用插件htmlWebpckPlugin并初始化,為html自定義引入的chunks:
entry:{ 
      page1:'./src/script/main.js', //可以被稱為chunk
      page2:'./src/script/a.js'
    },

plugins:[
        new htmlWebpckPlugin({
            template:'index.html' ,//根目錄
            filename:'page1.html',//自定義檔案名
            inject:'body',//自定義腳本位置 ,head 或body,false
            chunks:['page1','page2'] //為目前html自定義引入的chunks
        }),
        new htmlWebpckPlugin({
            template:'index.html' ,//根目錄
            filename:'page2.html',//自定義檔案名
            inject:'head',//自定義腳本位置 ,head 或body,false
            chunks:['page2']
        }),
    ]
           
webpack4.x深入了解
webpack4.x深入了解

此時在打包後的html中,可以看到根據模闆的配置而引入相應的chunks

  • 當chunk比較多的時候,可以用排除法來指定不需要引入的chunk,這個參數為excludeChunks:
webpack4.x深入了解

當指定排除page2時,生成的結果隻引入了page1

webpack4.x深入了解
  • 通過html-webpack-plugin的inline直接插入引用的檔案内容進而減少http請求
<!-- 直接取引入檔案的内容 -->
   <%=compilation.assets[htmlWebpackPlugin.files.chunks.page1.entry.substring(htmlWebpackPlugin.files.publicPath.length)].source() %>
           
webpack4.x深入了解

7.什麼是loader

  • loader的作用:

讓 webpack 能夠去處理那些非 JavaScript 檔案(webpack 自身隻了解 JavaScript)。loader 可以将所有類型的檔案轉換為 webpack 能夠處理的有效子產品,然後利用 webpack 的打包能力,對它們進行處理

  • 給檔案指定一個loader
module:{
			rules: [//使用babel-loader轉換es6代碼
				{
					test: /\.js$/,
					exclude: /node_modules/, //排除處理的檔案,減少耗時
					include:'/src',//指定打包範圍
					loader: "babel-loader",
					query:{
						presets: ["@babel/preset-env"]
					}
				}
			]
    },
           

 裡面包含兩個必須屬性:

test

 和 

use

。這告訴 webpack 編譯器(compiler) :當碰到「在 

require()

/

import

 語句中被解析為 '.js結尾' 的路徑時,在對它打包之前,先使用 

babel

 轉換一下

這時需要安裝一下babel和presets:

npm install --save-dev babel-loader @babel/core
npm install @babel/preset-env --save-dev
           

也可以在package.json檔案中定義轉碼:

webpack4.x深入了解

寫一個元件,用es6文法

webpack4.x深入了解

已将es6轉換成浏覽器能夠識别的語言

webpack4.x深入了解
  • 處理css檔案

首先安裝css-loader,上文提到過,安裝好了之後,用用loader處理:

{
	test: /\.css$/,//以.css結尾的檔案
	loader: "style-loader!css-loader",//css-loader引入檔案,style-loader在html中插入标簽
			}
           
webpack4.x深入了解
webpack4.x深入了解
  • 使用postcss-loader和autoprefixer給樣式加字首

首先安裝

npm install --save-dev  postcss-loader autoprefixer postcss
           
{
					test: /\.css$/,
					use: [
						'style-loader',
						{
							loader: 'css-loader',
							options: {
								importLoaders: 1,//指定引入資源的數量
							}
						},
						{
							loader: 'postcss-loader',
							options: {
								ident: 'postcss',
								plugins: [
									require('autoprefixer')({
										browsers:['last 5 versions']
									})
								]
							}
						}
					]
				}
           
webpack4.x深入了解
  • 使用less和sass

首選安裝less,less-loader和sass,sass-loader

npm i less //安裝less
npm i sass //安裝sass
npm install --save-dev less-loader less //安裝less-loader
npm install sass-loader node-sass webpack --save-dev
           

配置loader:

{
					test: /\.less$/, //  /\.scss$/
					use: [
						'style-loader','css-loader',
						{
							loader: 'postcss-loader',
							options: {
								ident: 'postcss',
								plugins: [
									require('autoprefixer')({
										browsers:['last 5 versions']
									})
								]
							}
						},
						{ loader: 'less-loader'} //less可以自己處理@import { loader: 'sass-loader'}
					]
				}
           

引入less檔案

webpack4.x深入了解

打包後已處理為css插入style标簽

webpack4.x深入了解
  • 處理模闆檔案

首先安裝html-loader:

npm i html-loader
           

配置html-loader:

{
					test: /\.(html)$/,
					use: {
						loader: 'html-loader',
					}
				}
           

在js中引用模闆檔案:

webpack4.x深入了解
webpack4.x深入了解

打包後模闆已插入到首頁中:

webpack4.x深入了解
  • ejs處理js模闆文法

首先安裝ejs-loader:

npm install ejs-loader
           

寫一個ejs模闆引擎:

webpack4.x深入了解

傳入參數:

webpack4.x深入了解

配置loader:

{ 
					test: /\.tpl$/, loader: 'ejs-loader',
				}
           
webpack4.x深入了解

此時已正确列印出結果

  • 處理圖檔檔案

首先安裝file-loader

npm install file-loader --save-dev
           

配置處理圖檔檔案的loader:

{ 
					test: /\.(png|jpg|gif|svg)$/i, loader: 'file-loader', //在樣式檔案中處理圖檔檔案
					options: {
						name: 'img/[name]-[hash:5].[ext]',//指定打包後的相對路徑和名稱
					},
				},
           

在一個less檔案中引入一張圖檔背景 

webpack4.x深入了解

此時file-loader已經處理為

webpack4.x深入了解

在根模闆可直接使用絕對路徑引入圖檔

<body>
  <img src='src/assets/3b676efb4b5a91ef347427790308f320290afdb1.jpg'>
   <div id='app'></div>
</body>
           

在模闆檔案中不能使用相對或絕對路徑引入圖檔,使用require的方式:

<img src=" ${require('../../assets/3b676efb4b5a91ef347427790308f320290afdb1.jpg')} ">
           
webpack4.x深入了解

使用url-loader根據圖檔大小來選擇打包方式

首先安裝url-loader:

npm install url-loader --save-dev
           

配置loader:

{ 
					test: /\.(png|jpg|gif|svg)$/i, //在樣式檔案中處理圖檔檔案
					loader: 'url-loader',
					options: {
						limit: 5000000 //如果檔案小于位元組限制,則可以傳回DataURL,否則傳回data:'xxx....'格式
					}
				},
           
webpack4.x深入了解

當圖檔大小大于limit值則傳回data:格式,此時打包的js檔案也會變大:

webpack4.x深入了解
webpack4.x深入了解

使用image-webpack-loader壓縮圖檔

首先安裝這個插件:

npm install image-webpack-loader --save-dev
           

配置加載器:

{ 
					test: /\.(gif|png|jpg|jpeg|svg)$/i, //在樣式檔案中處理圖檔檔案
					use:[
						'file-loader',
						{
							loader:"image-webpack-loader",//壓縮圖檔
							options: {
								disable: true, // [email protected] and newer
						  	webp: { //webp選項将啟用WEBP webp - 将JPG和PNG圖像壓縮為WEBP
									quality: 1055
								}
							},
						}
					]
		
				},
           

目前發現圖檔沒被壓縮小,?,是我配置錯了嗎