時間:2023-06-10 05:57:02 | 來源:網(wǎng)站運營
時間:2023-06-10 05:57:02 來源:網(wǎng)站運營
webpack打包詳解:yarn webpack
const path = require("path")module.exports = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output') // 一定要是絕對路徑 }}
module.exports = { entry: "./src/index.js", // 指定打包的路徑 output: { // 輸出文件設(shè)置 filename: "bundle.js", // 文件名 path: path.join(__dirname, 'output') // 絕對路徑 }, mode: "development" // 設(shè)置相關(guān)的執(zhí)行模式}
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 } ] }}
// 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}
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" } ] }}
{ test: /.png$/, use: { loader: "url-loader", options: { limit: 10 * 1024, esModule: false // 新版本file-loader的esModule屬性默認是true } } }
{ test: /.js$/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } }
@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版本 } }}
const marked = require("marked")module.exports = sourse => { const html = marked(sourse) // return `export default (${JSON.stringify(html)})` // 直接返回輸出的字符串, // 還可以 返回 html 字符串,交給下一個loader操作 return html}
const { CleanWebpackPlugin } = require("clean-webpack-plugin") // 導(dǎo)入插件module.exports = { plugins: [ // 配置插件的位置 new CleanWebpackPlugin() // 創(chuàng)建實例并且放到plugins數(shù)組中 ]}
// 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" })
new copyWebpackPlugin({ // 實例 copy插件 設(shè)置對象 patterns: [ // 設(shè)置地址 "public" // 指定的文件目錄 ] })
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 是必需的 } } } }) }}
yarn webpack --watch
yarn webpack-dev-server --open
module.exports = { devServer: { contentBase: ["public"] // 配置靜態(tài)路徑,可以是數(shù)組、字符串 } }
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 會以實際代理的主機名進行請求 } } }
devtool: "source-map" // 開發(fā)中配置的輔助工具
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` }) ] }})
const webpack = require("webpack")module.exports = { …… devServer: { hot: true // 開啟熱加載 }, plugins: [ new webpack.HotModuleReplacementPlugin() // 模塊熱加載插件 ]}
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);})
// hot: true,hotOnly: true,
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" // 指定的文件目錄 ] }) ]})
const webpack = require("webpack")module.exports = { entry: "./src/main.js", output: { filename: "main.js", }, mode: "none", plugins: [ new webpack.DefinePlugin({ API : JSON.stringify("123456") }) ]}
const webpack = require("webpack")module.exports = { ……, optimization : { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 minimize: true // 開啟壓縮 }}
module.exports = { ……, optimization : { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 concatenatemodules: true // 合并盡可能多的模塊 }}
module.exports = { ……, rules: [ { test: //.js$/, use: { loader: "babel-loader", options: { presets: [ ["@babel/preset-env", { modules: false }] // 默認屬性是modules屬性默認值是auto,自動轉(zhuǎn)換 ESM 插件是否開啟 ] } } } ], ……}
// webpack.config.jsmodule.exports = { ……, optimization: { // 集中配置webpack內(nèi)部優(yōu)化功能 usedExports: true, // 只輸出外部使用的成員 sideEffects: true, // 開啟副作用插件 // minimize: true // 開啟壓縮 }}// package.json{ ……, "sideEffects": false // 是否有副作用}
必須確保沒有副作用才能用false// package.json{ ……, "sideEffects": ["./src/a.js", "./src/*.css"] // 有副作用的文件}
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'] }) ]}
optimization: { splitChunks: { // 自動提取所有公共模塊到單獨 bundle chunks: 'all' } }
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) }) }}
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) }) }
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', }) ]}
new MiniCssExtractPlugin({ filename: "[name]-[hash:8].bundle.css" // :num 限制位數(shù) }
關(guān)鍵詞:打包
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。