国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁 > 營銷資訊 > 網(wǎng)站運營 > webpack打包詳解

webpack打包詳解

時間:2023-06-10 05:57:02 | 來源:網(wǎng)站運營

時間:2023-06-10 05:57:02 來源:網(wǎng)站運營

webpack打包詳解:

一、Webpack 打包

1.1 webpack 概述

yarn webpack

1.2 webpack 配置

1.2.1 webpack 配置文件

const path = require("path")module.exports = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output') // 一定要是絕對路徑 }}

1.2.2 webpack 工作模式

module.exports = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output') // 絕對路徑 }, mode: "development" // 設(shè)置相關(guān)的執(zhí)行模式}

1.2.3 webpack資源模塊加載

const path = require("path")module.exports = { entry: "./src/main.css", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output') // 絕對路徑 }, mode: "none", // 設(shè)置相關(guān)的執(zhí)行模式 module: { rules: [ // 針對其他資源的配置 { test: /.css$/, // 匹配打包的文件路徑 use: ["style-loader","css-loader" ] // 指定匹配到的文件需要執(zhí)行的loader } ] }}

1.2.4 webpack導(dǎo)入資源模塊

// main.jsimport creating from './header.js'import './main.css'const heading = creating()document.body.append(heading)// heading.jsimport "./heading.css"export default () => { const ele = document.createElement('h2') ele.textContent = "hello world" ele.classList.add("heading") ele.addEventListener("click", () => { alert("hello wepack") }) return ele}

1.2.5 webpack 文件資源加載器

const path = require("path")module.exports = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output'), // 絕對路徑 publicPath: "output/" // 加載的路徑 / 不能省略 }, mode: "none", // 設(shè)置相關(guān)的執(zhí)行模式 module: { rules: [ // 針對其他資源的配置 { test: /.css$/, // 匹配打包的文件路徑 use: ["style-loader","css-loader" ] // 指定匹配到的文件需要執(zhí)行的loader }, { test: /.png$/, use: "file-loader" } ] }}

1.2.6 data URL加載器

{ test: /.png$/, use: { loader: "url-loader", options: { limit: 10 * 1024, esModule: false // 新版本file-loader的esModule屬性默認是true } } }

1.2.7 加載器類型

1.2.8 Webpack 與 ES 2015

{ test: /.js$/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } }

1.2.9 webpack加載資源的方式

css-laoder加載資源的兩種方式

@import url(./heading.css); /* 加載資源樣式 */body { color: greenyellow; background-image: url(./icon.png); /* 先進行css-loader 發(fā)現(xiàn)其他格式的就交給其他格式的loader轉(zhuǎn)化 */ background-size: cover;}html加載資源,比如image標簽的src,不過需要先配置html-loader

{ test: /.html$/, use: { loader: 'html-loader', // 默認只會處理image標簽的src屬性 options: { atts: ['img:src', 'a:href'] // 手動設(shè)置加載的標簽和標簽屬性,需要html-loader是0.5.5版本 } }}

1.2.10 webpack核心工作原理

1.2.11 開發(fā)一個 loader

兩種方法

其實loader就是管道

const marked = require("marked")module.exports = sourse => { const html = marked(sourse) // return `export default (${JSON.stringify(html)})` // 直接返回輸出的字符串, // 還可以 返回 html 字符串,交給下一個loader操作 return html}

1.3 webpack常用插件

1.3.1 自動清除插入目錄插件

const { CleanWebpackPlugin } = require("clean-webpack-plugin") // 導(dǎo)入插件module.exports = { plugins: [ // 配置插件的位置 new CleanWebpackPlugin() // 創(chuàng)建實例并且放到plugins數(shù)組中 ]}

1.3.2 自動生成使用打包結(jié)果的html

// plugins 數(shù)組中的設(shè)置new HtmlWebpackPlugin({ title: "webpack plugin sample", // 設(shè)置html文件的title主體 meta: { viewport: "width=device-width" // 視口寬度 }, template: "./src/index.html" // 參照的模板 })./src/index.html

<h1><%= htmlWebpackPlugin.options.title %></h1>new HtmlWebpackPlugin({ filename: "about.html" })

1.3.3 靜態(tài)資源打包器

new copyWebpackPlugin({ // 實例 copy插件 設(shè)置對象 patterns: [ // 設(shè)置地址 "public" // 指定的文件目錄 ] })

1.3.4 開發(fā)一個插件







class myPlugin { apply (compliter) { console.log("啟動"); compliter.hooks.emit.tap("mypl", compilation => { // 注冊函數(shù),emit是輸出文件前的事件掛載點 // compilitation 可以理解為此次打包的上下文,打包產(chǎn)生的過程中產(chǎn)生的結(jié)果都在這個數(shù)據(jù)中 for (const name in compilation.assets) { // console.log(name); // 獲取文件名 // console.log(compilation.assets[name].source()); // 獲取文件內(nèi)容 if (name.endsWith(".js")) { const contents = compilation.assets[name].source() const withComment = contents.replace(////*/*+///g, "") compilation.assets[name] = { source: () => withComment, // source 是將來要操作的數(shù)據(jù) size: () => withComment.length // size 是必需的 } } } }) }}

1.4 webpack 提升開發(fā)體驗

  1. 提供source Map 支持

1.4.1 實現(xiàn)自動編譯

yarn webpack --watch

1.4.2 實現(xiàn)自動刷新

yarn webpack-dev-server --open

1.4.3 webpack Dev Server 靜態(tài)資源訪問

module.exports = { devServer: { contentBase: ["public"] // 配置靜態(tài)路徑,可以是數(shù)組、字符串 } }

1.4.4 webpack Dev Server 代理API服務(wù)

devServer: { contentBase: ["public"], // 配置靜態(tài)路徑,可以是數(shù)組、字符串 proxy: { // 用于配置代理的配置 "/api": { // 代理的請求路徑前綴 // http://localhost:8080/api/user 相對于 https://api.github.com/api/user, 所有需要重寫 target: "https://api.github.com", // 代理的目標 pathRewrite: { // 代理路徑的重寫 // http://localhost:8080/api/user 相對于 https://api.github.com/user "^/api": "" // 將代理到的路徑中以 /api 開頭的路由替換為空 }, // 默認為 false 不能使用 localhost:8080 作為請求 gitHub 主機名 changeOrigin: true // true 會以實際代理的主機名進行請求 } } }

1.5 Source Map

1.5.1 源代碼地圖

1.5.2 webpack 配置 Source Map

devtool: "source-map" // 開發(fā)中配置的輔助工具

1.5.3 eval 模式

devtool: "eval"const HtmlWebpackPlugin = require("html-webpack-plugin")const allModes = [ 'eval', 'cheap-eval-source-map', 'cheap-module-eval-source-map', 'eval-source-map', 'cheap-source-map', 'cheap-module-source-map', 'inline-cheap-source-map', 'inline-cheap-module-source-map', 'source-map', 'inline-source-map', 'hidden-source-map', 'nosources-source-map']module.exports = allModes.map(item => { return { mode: "none", devtool: item, entry: "./src/index.js", output: { filename: `js/${item}.js` }, module: { rules: [ { test: //.js$/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } } ] }, plugins: [ new HtmlWebpackPlugin({ filename: `${item}.html` }) ] }})

1.6 webpack HMR

1.6.1 HMR開啟

const webpack = require("webpack")module.exports = { …… devServer: { hot: true // 開啟熱加載 }, plugins: [ new webpack.HotModuleReplacementPlugin() // 模塊熱加載插件 ]}

1.6.2 HMR API

let lastHeader = heading // 獲取舊元素module.hot.accept("./header.js", () => { const value = lastHeader.innerHTML // 獲取狀態(tài) document.body.remove(lastHeader) const newHeading = creating() newHeading.innerHTML = value // 將狀態(tài)賦值給新的元素 document.body.append(newHeading) lastHeader = newHeading})import icon from "./icon.png"module.hot.accept("./icon.png", () => { img.src = icon console.log(icon);})

1.6.3 HMR 注意事項

// hot: true,hotOnly: true,

1.7 生產(chǎn)環(huán)境優(yōu)化

1.7.1 不同環(huán)境下的配置

module.exports = (env, argv) => { // 環(huán)境名,運行過程中的所有參數(shù) const config = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "js/bundle.js", // 文件名 path: path.join(__dirname, 'dist'), // 絕對路徑 // publicPath: "dist/" // 加載的路徑 / 不能省略 }, mode: "development", // 設(shè)置相關(guān)的執(zhí)行模式 devtool: "eval", // 開發(fā)中配置的輔助工具 devServer: { hot: true, // hotOnly: true, contentBase: ["public"], // 配置靜態(tài)路徑,可以是數(shù)組、字符串 }, module: { rules: [ // 針對其他資源的配置 { test: //.css$/, use: ["style-loader", "css-loader"] }, { test: //.png/, use: { loader: "url-loader", options: { limit: 10 * 1024, esModule: false } } }, { test: //.js$/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } } ] }, plugins: [ // 配置插件的位置 new HtmlWebpackPlugin({ title: "webpack plugin sample", // 設(shè)置html文件的title主體 meta: { viewport: "width=device-width" // 視口寬度 }, template: "./src/index.html" // 參照的模板 }), new webpack.HotModuleReplacementPlugin() ] } // 開發(fā)模式 if (env === "production") { config.mode = "production" config.devtool = false config.plugins = [ new CleanWebpackPlugin(), new CopyWebpackPlugin(['public']), ...config.plugins ] } return config}// webpack.prod.jsconst common = require("./webpack.common")const { merge } = require("webpack-merge")const { CleanWebpackPlugin } = require("clean-webpack-plugin")const CopyWebpackPlugin = require("copy-webpack-plugin");module.exports = merge(common, { // merge 類似于 assign(),但是merge可以用于重新改變值,并且是新的空間 mode: 'production', plugins: [ new CleanWebpackPlugin(), new CopyWebpackPlugin({ // 實例 copy插件 設(shè)置對象 patterns: [ // 設(shè)置地址 "public" // 指定的文件目錄 ] }) ]})

1.7.2 definePlugin

const webpack = require("webpack")module.exports = { entry: "./src/main.js", output: { filename: "main.js", }, mode: "none", plugins: [ new webpack.DefinePlugin({ API : JSON.stringify("123456") }) ]}

1.8 代碼優(yōu)化配置—optimization

1.8.1 tree shaking (搖樹)

const webpack = require("webpack")module.exports = { ……, optimization : { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 minimize: true // 開啟壓縮 }}

1.8.2 合并模塊

module.exports = { ……, optimization : { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 concatenatemodules: true // 合并盡可能多的模塊 }}

1.8.3 tree-shaking 與 babel

module.exports = { ……, rules: [ { test: //.js$/, use: { loader: "babel-loader", options: { presets: [ ["@babel/preset-env", { modules: false }] // 默認屬性是modules屬性默認值是auto,自動轉(zhuǎn)換 ESM 插件是否開啟 ] } } } ], ……}

1.8.4 sideEffects —副作用

// webpack.config.jsmodule.exports = { ……, optimization: { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 sideEffects: true, // 開啟副作用插件 // minimize: true // 開啟壓縮 }}// package.json{ ……, "sideEffects": false // 是否有副作用}必須確保沒有副作用才能用false

否則用數(shù)組標注有副作用的文件

// package.json{ ……, "sideEffects": ["./src/a.js", "./src/*.css"] // 有副作用的文件}

1.9 code splitting—代碼分包

1.9.1 多入口打包

module.exports = { mode: 'none', entry: { index: './src/index.js', album: './src/album.js' }, output: { filename: '[name].bundle.js' // [name]會動態(tài)命名 }, ……, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: 'Multi Entry', template: './src/index.html', filename: 'index.html', chunks: ['index'] // 允許插入到模板中的chunks }), new HtmlWebpackPlugin({ title: 'Multi Entry', template: './src/album.html', filename: 'album.html', chunks: ['album'] }) ]}

1.9.2 提取公共模塊

optimization: { splitChunks: { // 自動提取所有公共模塊到單獨 bundle chunks: 'all' } }

1.9.3 動態(tài)導(dǎo)入

const render = () => { const hash = window.location.hash || '#posts' const mainElement = document.querySelector('.main') mainElement.innerHTML = '' if (hash === "#post") { import("./posts/posts.js").then(({ default: posts }) => { // 獲取成員 document.body.appendChild(posts) }) } else if (hash === "#album") { import("./album/album.js").then(({ default: album }) => { document.body.appendChild(album) }) }}

1.9.4 魔法注釋

if (hash === "#post") { import(/*webpackChunkName: "auble" */"./posts/posts.js").then(({ default: posts }) => { document.body.appendChild(posts) }) } else if (hash === "#album") { import("./album/album.js").then(({ default: album }) => { document.body.appendChild(album) }) }





1.9.5 MiniCssExtractPlugin

const { CleanWebpackPlugin } = require('clean-webpack-plugin')const HtmlWebpackPlugin = require('html-webpack-plugin')const MiniCssExtractPlugin = require("mini-css-extract-plugin")module.exports = { mode: 'none', entry: { main: './src/index.js' }, output: { filename: '[name].bundle.js' }, module: { rules: [ { test: //.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] } ] }, plugins: [ new CleanWebpackPlugin(), new MiniCssExtractPlugin({ linkType: 'text/css', }) ]}

1.9.6 optimize-css-assets-webpack-plugin

1.10 輸出文件名hash

new MiniCssExtractPlugin({ filename: "[name]-[hash:8].bundle.css" // :num 限制位數(shù) }

關(guān)鍵詞:打包

74
73
25
news

版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點擊下載Chrome瀏覽器
關(guān)閉