日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

webpack4打包工具

發(fā)布時間:2025/3/8 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 webpack4打包工具 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

什么是webpack

webpack 是一個現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊打包器(module bundler)。當(dāng) webpack 處理應(yīng)用程序時,它會遞歸地構(gòu)建一個依賴關(guān)系圖(dependency graph),其中包含應(yīng)用程序需要的每個模塊,然后將所有這些模塊打包成一個或多個 bundle

可以做的事情

代碼轉(zhuǎn)換、文件優(yōu)化、代碼分割、模塊合并、自動刷新、代碼校驗、自動發(fā)布 復(fù)制代碼

需要提前掌握的內(nèi)容

  • 需要node基礎(chǔ),以及npm的使用
  • 掌握es6語法

主要學(xué)習(xí)webpack哪些內(nèi)容

  • webpack常見配置
  • webpack高級配置
  • webpack優(yōu)化策略
  • ast抽象語法樹
  • webpack中的Tapable
  • 掌握webpack流程,手寫webpack
  • 手寫webpack中常見的loader
  • 手寫webpack中常見的plugin

創(chuàng)建文件

mkdir webpack-test && cd webpack-test mkdir src touch src/index.js 復(fù)制代碼

初始化文件

npm init -y 初始文件(默認(rèn)的) npm init 復(fù)制代碼

開始打包

npx webpack 復(fù)制代碼

配置webpack.config.js

touch webpack.config.jsconst path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {devServer: { // 開發(fā)服務(wù)器的配置contentBase: path.join(__dirname, 'dist'),compress: true,port: 3000},mode: 'development', // 模式 默認(rèn)兩種production developmententry: './src/index.js', //入口output: {filename: 'bundle.js', //打包后的文件名path: path.resolve(__dirname, 'dist'), //路徑必須是一個絕對路徑},plugins: [// 數(shù)組放著所有的webpack插件new HtmlWebpackPlugin({template: './src/index.html',filename: 'index.html'})] } 復(fù)制代碼

index.html

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><div id="root"></div><script src="bundle.js"></script> </body> </html> 復(fù)制代碼

index.js

var root = document.getElementById("root"); root.innerHTML="你好" 復(fù)制代碼

webpack常見配置

npm i webpack webpack-cli -D npm i html-webpack-plugin -D 復(fù)制代碼

使用模板 html

  • html-webpack-plugin 可以指定template模板文件,將會在output目錄下,生成html文件,并引入打包后的js.
npm i html-webpack-plugin -D 復(fù)制代碼

webpack-dev-server

  • webpack-dev-server提供了一個簡單的Web服務(wù)器和實時熱更新的能力
npm i webpack-dev-server -D 復(fù)制代碼

pagkage.js

{"name": "webpack-test","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","dev": "webpack-dev-server","build": "webpack"},"keywords": [],"author": "","license": "ISC","devDependencies": {"html-webpack-plugin": "^3.2.0","webpack": "^4.30.0","webpack-cli": "^3.3.0","webpack-dev-server": "^3.3.1"} }復(fù)制代碼

目前的目錄

啟動項目

npm run dev 復(fù)制代碼

瀏覽器輸入http://localhost:3000/

加載樣式文件

  • 在src目錄下創(chuàng)建一個index.css
body{background-color:red; } 復(fù)制代碼
  • 在index.js中引入index.css
require('./index.css'); 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
module: { //模塊rules: [ // 規(guī)則 css-loader // style-loader 把css插入到head的標(biāo)簽中// loader的特點: 希望單一// loader的用法: 字符串只用一個loader// 多個loader需要[]// loader的順序 默認(rèn)是從右向左執(zhí)行// loader還可以寫出對象方式{test: /\.css$/,use: ['style-loader','css-loader']},] } 復(fù)制代碼
  • css-loader style-loader
npm i css-loader style-loader -D 復(fù)制代碼
  • 效果如下

加載less(sass,stylus類似)

  • 在src目錄下創(chuàng)建一個index.less
body{#root{border:1px yellow solid;color: #000;} } 復(fù)制代碼
  • 在index.js中引入index.less
require('./index.css'); 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
{test: /\.less$/,use: [{loader: 'style-loader',},'css-loader','less-loader']}, 復(fù)制代碼
  • less-loader
npm i less less-loader -D 復(fù)制代碼
  • 效果如下

提取單獨打包css文件

npm i mini-css-extract-plugin -D 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
const MiniCssExtractPlugin = require('mini-css-extract-plugin');plugins: [ new MiniCssExtractPlugin({filename: 'main.css'})], module: { //模塊use: [MiniCssExtractPlugin.loader,]},{test: /\.less$/,use: [MiniCssExtractPlugin.loader,]}]} 復(fù)制代碼

css3樣式自動加前綴

npm i postcss-loader autoprefixer -D 復(fù)制代碼
  • 在webpack-test創(chuàng)建postcss.config.js
module.exports = {plugins: [require('autoprefixer')] } 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
{test: /\.css$/,use: [{loader: 'style-loader',// options: {// insertAt: 'top' //內(nèi)聯(lián)樣式最高級// }},'css-loader','postcss-loader']},{test: /\.less$/,use: [{loader: 'style-loader',},'css-loader','postcss-loader','less-loader'] } 復(fù)制代碼

轉(zhuǎn)化es6語法

npm i babel-loader @babel/core @babel/preset-env -D npm i @babel/plugin-proposal-class-properties -D 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
rules: [ { test: /\.js$/, use: {loader: 'babel-loader',options: { // 用babel-loader 需要把es6-es5presets: ['@babel/preset-env'],plugins: ['@babel/plugin-proposal-class-properties']} } ] 復(fù)制代碼

全局變量引入

npm i jquery -D npm i expose-loader -D 復(fù)制代碼

第一種

  • import $ from 'jquery';
  • webpack.config.js增加一些參數(shù)
rules: [ {test: require.resolve('jquery'),use: 'expose-loader?$'}, ] 復(fù)制代碼

第二種

  • webpack.config.js增加一些參數(shù)
const webpack = require('webpack'); plugins: [ // 數(shù)組放著所有的webpack插件new webpack.ProvidePlugin({$: 'jquery' // 在每個模塊中注入$對象}) ], 復(fù)制代碼

引入圖片處理

// 1.在js中創(chuàng)建圖片來引入 // 2.在css引入backgroud('url') // 3.<img src="" alt="" />> npm i file-loader -D npm i html-withimg-loader -D 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
rules: [ {test: /\.html$/,use: 'html-withimg-loader'},{test: /\.(png|jpg|gif)$/,use: 'file-loader'}, ] 復(fù)制代碼
  • 限制圖片大小
npm i url-loader -D 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
{test: /\.(png|jpg|gif)$/,use: {loader: 'url-loader',options: {limit: 200*1024}} 復(fù)制代碼

images和css打包分類

  • webpack.config.js增加一些參數(shù)
plugins: [ // 數(shù)組放著所有的webpack插件new MiniCssExtractPlugin({filename: 'css/main.css'}), ], {test: /\.(png|jpg|gif)$/,use: {loader: 'url-loader',options: {limit: 1,outputPath: '/img/',publicPath: 'https://www.baidu.com' // 在圖片上加域名}} 復(fù)制代碼

多頁面打包

  • 在scr創(chuàng)建一個other.js
console.log("other 一路走好!") 復(fù)制代碼
  • webpack.config.js增加一些參數(shù)
// 多入口 entry: {index: './src/index.js', home: './src/other.js', }, output: {filename: '[name].js', //打包后的文件名path: path.resolve(__dirname, 'dist'), //路徑必須是一個絕對路徑// publicPath: 'https://www.baidu.com' }, plugins: [ // 數(shù)組放著所有的webpack插件new HtmlWebpackPlugin({template: './src/index.html',filename: 'index.html',chunks: ['index']}),new HtmlWebpackPlugin({template: './src/index.html',filename: 'home.html',chunks: ['home']}), ] 復(fù)制代碼

配置source-map調(diào)試代碼

  • webpack.config.js增加一些參數(shù)
output: {filename: '[name].js', //打包后的文件名path: path.resolve(__dirname, 'dist'), //路徑必須是一個絕對路徑// publicPath: 'https://www.baidu.com' }, // devtool: 'source-map', // 1.增加映射文件 可以幫我們調(diào)試源代碼 // devtool: 'eval-source-map', // 2.不會產(chǎn)生單獨的文件,但是可以顯示行和列 // devtool: 'cheap-module-source-map', // 3.不會產(chǎn)生列,但是是一個單獨的映射文件(產(chǎn)生后你可以保留起來) devtool: 'cheap-module-eval-source-map',// 4.不會長生文件,集成在打包后的文件中不會產(chǎn)生列 復(fù)制代碼

watch實時打包

  • webpack.config.js增加一些參數(shù)
entry: {index: './src/index.js', home: './src/other.js', }, watch: true, watchOptions: { // 監(jiān)控的選項poll: 1000, // 每秒問我1000次aggregateTimeout: 500, // 防抖ignored: /node_modules/ // 不需要進(jìn)行監(jiān)控哪個文件 }, 復(fù)制代碼

常用的小插件

  • 清除dist (clean-webpack-plugin)
  • 拷貝文件(copy-webpack-plugin)
  • 版權(quán)注釋(bannerPlugin)
npm i clean-webpack-plugin -D npm i copy-webpack-plugin -D 復(fù)制代碼
  • 在webpack-test創(chuàng)建doc文件,里面創(chuàng)建hello.txt
  • webpack.config.js增加一些參數(shù)
const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); plugins: [ new CleanWebpackPlugin(),new CopyWebpackPlugin([{from: 'doc', to: './'}]),new webpack.BannerPlugin('cl by 2019') ], 復(fù)制代碼

webpack跨域問題

npm i express -D 復(fù)制代碼
  • 1)webpack代理
  • 在webpack-test目錄下創(chuàng)建server.js
let express = require('express'); let app = express(); app.get('/user', (req, res)=> {res.json({ name: "xiaolin3333" }) }) app.listen(3000); 復(fù)制代碼
  • webpack.config.js配置
devServer: { // 開發(fā)服務(wù)器的配置// 1)http:proxyproxy: {// 重新的方式 把請求代理到express服務(wù)器!'/api': {target: 'http://localhost:3000',pathRewrite: {'/api': ''}} // 配置了一個代理}}, 復(fù)制代碼
  • index.js
let xhr = new XMLHttpRequest();xhr.open('GET', '/api/user', true);xhr.onload = function() {console.log(xhr.response,); }xhr.send(); 復(fù)制代碼
  • 啟動 node server.js && npm run dev
  • 2)前端只想單純來模擬數(shù)據(jù)
  • webpack.config.js配置
devServer: { // 開發(fā)服務(wù)器的配置// 2)前端只想單純來模擬數(shù)據(jù)before(app) { // 提供的方法 鉤子app.get('/user', (req, res)=> {res.json({ name: "xiaolinwww" })})} 復(fù)制代碼
  • index.js
let xhr = new XMLHttpRequest(); xhr.open('GET', '/user', true);xhr.onload = function() {console.log(xhr.response,); }xhr.send(); 復(fù)制代碼
  • 啟動 npm run dev
  • 3)有服務(wù)端 不想用代理來處理 能不能再服務(wù)端中啟動webpack端口用服務(wù)端口
npm i webpack-dev-middleware -D 復(fù)制代碼
  • server.js
let express = require('express');let app = express(); let webpack = require('webpack');// 中間件 let middle = require('webpack-dev-middleware');let config = require('./webpack.config');let compiler = webpack(config);app.use(middle(compiler));app.get('/user', (req, res)=> {res.json({ name: "xiaolin3333-webpack-dev-middleware" }) })app.listen(3000); 復(fù)制代碼
  • index.js
let xhr = new XMLHttpRequest(); xhr.open('GET', '/user', true);xhr.onload = function() {console.log(xhr.response,); }xhr.send(); 復(fù)制代碼
  • 啟動 node server && http://localhost:3000/

resolve屬性的配置

yarn add css-loader style-loader -D 復(fù)制代碼
  • index.js
import './style';style.cssbody{background-color:green;transform: rotate(90deg); } 復(fù)制代碼
  • webpack.config.js配置
resolve: {// 解析第三方包 commonmodules: [path.resolve('node_modules')],extensions: ['.js','.css','.vue'] // alias: { // 別名 vue vue.runtime // bootstrap: 'bootstrap/dist/css/bootstrap.css' // }, // mainFields: ['style', 'main'] // mainFields: [],// 入口文件的名字index.js },module: { //模塊rules: [ {test: /\.css$/,use: ['style-loader','css-loader']},] } 復(fù)制代碼

項目文件未更新

  • github.com/chenlin1/we…

今天到此結(jié)束,明天更新。。。。

總結(jié)

以上是生活随笔為你收集整理的webpack4打包工具的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。