In vue, webpack can package js, css, pictures, json and other files into appropriate formats for browser use; in webpack, js, css, pictures, json and other file types can be packaged Use it as a module. Various module resources in webpack can be packaged and merged into one or more packages, and during the packaging process, the resources can be processed, such as compressing images, converting scss to css, converting ES6 syntax to ES5, etc., which can be recognized by HTML. file type.
The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.
1. What is webpack
The definition given by the webpack official website is
Essentially, webpack is a modern JavaScript application Static module bundler. When webpack processes an application, it recursively builds a dependency graph that contains every module the application needs, and then packages all these modules into one or more bundles.
#As shown above: The blue block in the middle is webpack. It will package various files on the left into files that can be parsed by HTML on the right.
Summary:
#webpack is a static packaging module.
There are two concepts involved here: Packaging and Module
1. What is a module?
There are many specifications for modularization, such as commonJs specification, AMD specification, CMD specification, ES6 specification, etc.
Before ES6, if you want to use modular development , we need to use other tools, and after the development is completed, we need to deal with various dependencies and integrate and package them.
Webpack allows us to carry out modular development. It provides a platform and will help We deal with the dependencies between each module.
Webpack will eventually help us package js, css, pictures, json and other files into a suitable format for use by the browser.
In webpack, the above file types are all Can be used as a module.
2. What is packaging?
It is to package various module resources in webpack Merge into one or more packages. And during the packaging process, resources can be processed, such as: compressing images, converting scss to css, converting ES6 syntax to ES5 and other file types that can be recognized by html.
2. Installation of webpack packaging tool
The webpack packaging tool depends on nodejs. The nodejs environment depends on various packages, and these packages are managed using npm. What is npm? npm is used to manage various packages under node
Let’s see how to install webpack?
The first step: install nodejs
Download nodejs from the official website: https://nodejs.org/zh-cn/ After installation, you can check the nodejs version
node -v
My current version is v12 .16.2
When nodejs is installed by default, npm will be installed automatically, so npm does not need to be installed separately
Step 2: Install webpack
The webpack version I use is 3.6.0, because the version of vue I am currently using is 2, and the webpack version that vue2 depends on is 3.6.0
First check whether the machine has been installed For webpack, use the command to query
webpack --version
If it is not installed, install global webpack
npm install webpack@3.6.0 -g -g:表示的是global 全局的意思
webpack需要全局安裝, 也需要局部安裝.
我們在終端或者IDE的terminal中使用webpack都是使用的全局的webpack,當(dāng)我們在項(xiàng)目下使用package.json scripts webpacks, 這時候使用的是局部安裝的.
那什么是全局webpack ,什么是本地webpack呢?
我們通常都會安裝兩個webpack, 一個是全局的一個是本地的.
全局的指的是電腦上安裝的webpack包, 所有項(xiàng)目都可以使用
本地webpack是指當(dāng)前項(xiàng)目的webpack包. 通常全局webpack版本會比較高, 而我的項(xiàng)目是老項(xiàng)目, 使用的是老版本的
webpack打包的, 這時如果使用全局的webpack打包就會報錯, 所以, 需要安裝一個和項(xiàng)目匹配的本地的webpack包
在這里, 我們先值安裝全局的, 后面使用到本地的了, 再來安裝本地的webpack.
三. webpack的基本使用
webpack下通常包含兩個文件夾, 一個是src, 一個是dist
- src下都會有一個main.js, 作為主js文件.
- dist存放打包后的文件
在webpack中,我們會使用兩種類型的模板來定義: 分別是commonJs語法, 和ES6語法.
- 在main.js引用mathUtil.js, 使用commonjs語法
- 在main.js引用dataUtil.js, 使用ES6語法
下面, 我們創(chuàng)建一個mathUtil.js 和 dataUtil.js兩個js文件, 分別使用commonJs語法和ES6語法來創(chuàng)建.
- 在main.js引用mathUtil.js, 使用commonJs語法
- - 在main.js引用dataUtil.js, 使用ES6語法
項(xiàng)目結(jié)構(gòu)如下:
1) 使用commonJs語法
第一步: 在mathUtil.js中export, 使用commonJs模塊的寫法 : module.exports ={add, sub}
function add(num1, num2) { return num1 + num2 } function sub(num1, num2) { return num1 - num2 } // 使用commonJs導(dǎo)出模塊 module.exports={add, sub}
這里使用的是commonJs的語法導(dǎo)出方法
第二步: 在main.js中引用mathUtil.js中導(dǎo)出的變量 const {add, sub} = require("文件名")
const{add, sub} = require("./mathUtil.js") console.log(add(10, 20)) console.log(sub(20, 10))
第三步: 使用webpack語句打包 : webpack ./src/main.js ./dist/bundle.js
首先進(jìn)入到當(dāng)前項(xiàng)目的根目錄下, 然后輸入命令
webpack ./src/main.js ./dist/bundle.js
意思是: 將src目錄下的main.js進(jìn)行打包, 打包好的文件放在dist目錄下, 并命名為bundle.js
webpack是自動打包工具, 所以, 我們只需要打包main.js, 他會自動檢查main.js是否引用了其他文件. 如果有自動將其打包.
打包以后, 會生成一個bundle.js.
第四步: 在index.html中引入bundle.js文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./dist/bundle.js" ></script> </head> <body> </body> </html>
引入以后, 就是普通的html代碼了, 我們可以向訪問其他html一樣,訪問這個頁面.
2) 使用ES6語法
第一步: 在dateUtil.js中導(dǎo)出, 使用ES6寫法: export {var1, var2}
function priceUnit(price) { return "$" + price.toFixed(2) } export {priceUnit}
第二步: 在main.js中引用dateUtil.js中導(dǎo)出的變量 import {var1, var2} from "文件地址"
import {priceUnit} from "./dataUtil"console.log(priceUnit(25))
第三步: 使用webpack語句打包 : webpack ./src/main.js ./dist/bundle.js
webpack ./src/main.js ./dist/bundle.js
第四步: 在index中引用bundle.js文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./dist/bundle.js" ></script> </head> <body> </body> </html>
四. webpack配置文件
1. 如何使用webpack命令直接打包
剛剛我們打包的時候, 使用的是
webpack ./src/main.js ./dist/bundle.js
那么, 如果在項(xiàng)目下, 可不可以直接使用webpack, 而不用每次都指定文件呢? 這樣可以方便很多
當(dāng)然是可以的, 我們需要在項(xiàng)目根目錄下創(chuàng)建一個文件: webpack.config.js 這個名字是固定的
這個js就是要告訴我們哪里是webpack的入口, 哪個是webpack的出口
webpack.config.jsmodule.export={ entry: './src/main.js', output: { path: '/dist', filename: '/bundle.js' } }
- entry用來指定入口, 指定一個路徑
- output用來指定出口. 需要注意的是: 出口是一個對象, 由兩部分組成: path和filename
然后我們在終端輸入webpack打包. 打包會報錯, 報錯信息提示很明確:
The provide value "./dist" is not an absolute path!
意思是說path應(yīng)該是已經(jīng)絕對路徑. 也就是dist的絕對路徑
思考: 我們能直接寫一個絕對路徑么? 比如: /Users/workspace/vue-study/webpack的配置/src/main.js 這樣可以么?
這樣肯定不太好, 因?yàn)槲乙坏⑽募脑谄渌夸浵? 這個地址就變了.
webpack可以幫助我們獲取當(dāng)前項(xiàng)目的絕對路徑
我們const path = require("path")來獲取相對目錄. 可是當(dāng)前目錄下沒有path的包, path是node下東西, 需要通過npm init來初始化,
2. 初始化項(xiàng)目npm init
初始化命令
npm init
初始化完成以后, 就會創(chuàng)建一個叫package.json的文件
通常, 我們需要使用node的東西, 或者單獨(dú)依賴node環(huán)境的話, 都會執(zhí)行npm init, 生成package.json
3. 安裝模塊
如果package.json里面依賴其他模塊, 需要使用npm install的安裝一下, 然后就會在當(dāng)前文件夾中安裝一些東西
npm install
- const path = require("path")這里的path就是node給我們生成的, 我們可以直接使用.
然后我們的output中path就可以這么寫:
path.resovle(__dirname, "dist")
- _dirname是一個全局變量, resolve是一個函數(shù), 可以將兩個部分的內(nèi)容拼在一塊, 這樣生成以后就是一個絕對路徑
4. 使用npm run來啟動項(xiàng)目
下面來看一下package.json
{ "name": "meet", "version": "1.0.0", "description": "剛剛我們打包的時候, 使用的是webpack ./src/main.js ./dist/bundle.js 那么, 如果在項(xiàng)目下, 可不可以直接使用webpack, 而不用每次都指定文件呢? 可以的, 我們需要在項(xiàng)目根目錄下創(chuàng)建一個文件, webpack.config.js 這個名字是固定的 這個js就是要告訴我們哪個是webpac的入口, 哪個是webpack的出口 通過module.export={ entry: './src/main.js', output: { path: '/dist', filename: '/bundle.js' } } 來告訴我們?nèi)肟诤统隹谠谀睦? entry用來指定入口, 指定一個路徑 output用來指定出口. 出口是一個對象", "main": "webpack.config.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
通常我們啟動項(xiàng)的時候會使用npm run serve啟動項(xiàng)目, npm run build構(gòu)建項(xiàng)目. 當(dāng)執(zhí)行這個命令的時候, 就會去package.json中的script標(biāo)簽中找build命令和serve命令.
執(zhí)行npm run build讓其執(zhí)行webpack打包就可以在script中增加"build":"webpack"
{ "name": "meet", "version": "1.0.0", "description": "剛剛我們打包的時候, 使用的是webpack ./src/main.js ./dist/bundle.js 那么, 如果在項(xiàng)目下, 可不可以直接使用webpack, 而不用每次都指定文件呢? 可以的, 我們需要在項(xiàng)目根目錄下創(chuàng)建一個文件, webpack.config.js 這個名字是固定的 這個js就是要告訴我們哪個是webpac的入口, 哪個是webpack的出口 通過module.export={ entry: './src/main.js', output: { path: '/dist', filename: '/bundle.js' } } 來告訴我們?nèi)肟诤统隹谠谀睦? entry用來指定入口, 指定一個路徑 output用來指定出口. 出口是一個對象", "main": "webpack.config.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" }, "author": "", "license": "ISC" }
然后就可以使用npm run webpack來打包了. 但是這里打包是全局打包. 因?yàn)槲覀冎爸话惭b了一個全局的webpack.
但如果項(xiàng)目使用的版本和全局的不一樣, 怎么辦呢? 我們還可以使用局部的wenpack打包.
5. 全局webpack和局部webpack有什么區(qū)別呢?
我們通常都會安裝兩個webpack,
- 一個是全局的
- 一個是本地的.
全局的指的是電腦上安裝的webpack包, 所有項(xiàng)目都可以使用
本地webpack是指當(dāng)前項(xiàng)目的webpack包.
通常全局webpack版本會比較高, 而我的項(xiàng)目是老項(xiàng)目, 使用的是老版本的
webpack打包的, 這時如果使用全局的webpack打包就會報錯, 所以, 需要安裝一個和項(xiàng)目匹配的本地的webpack包
6. 安裝本地webpack命令
npm install webpack@3.6.0 --save-dev
- --save-dev: 這個參數(shù)的含義表示開發(fā)時依賴.
這里有兩個概念:
- 1. 開發(fā)時依賴
- 2. 運(yùn)行時依賴
對于打包來說, 我們只有在開發(fā)環(huán)境才會打包, 開發(fā)好以后要上線了會將其構(gòu)建成html代碼, 放到服務(wù)器上運(yùn)行,
放到服務(wù)器以后, 就不需要打包了, 所以, 打包只需要在開發(fā)時使用, 是一個開發(fā)時依賴
本地webpack安裝好以后, 會在package.json中看到devDependencies屬性, 這就是開發(fā)時依賴
本地webpack安裝好以后, 使用npm run build進(jìn)行打包. 那是使用的全局webpack打包的還是本地webpack打包的呢?
本地安裝好webpack以后會多出一個文件夾node_modules, 這里是默認(rèn)在本地裝的包, 其中有一個是webpack, 使用這里面的webpack
就表示使用的局部webpack打包. 而當(dāng)我們在終端, 或者ide的terminal中執(zhí)行webpack命令都是全局的
如果想要使用局部webpack打包, 可以使用npm run build. 這時就是去package.json的script腳本中找build命令了.
package.json中腳本命令執(zhí)行的順序:
- 首先, 在本地的路徑中找命令
- 然后, 本地沒有, 再去全局中找命令
在這里首先回去本地找有沒有這個命令, 如果沒有就去全局找
五.使用webpack打包c(diǎn)ss文件
webpack主要是用來打包的, 我們之前都是打包了js代碼文件, 那如果還有css, 圖片, 或者一些高級轉(zhuǎn)換,如將ES6轉(zhuǎn)換成ES5,將scss, less轉(zhuǎn)成css, 將.vue文件轉(zhuǎn)換成js文件怎么辦呢?
webpack單獨(dú)是不能完成轉(zhuǎn)換的,需要借助loader.
1. 什么是紹loader?
webpack 可以使用 loader 來預(yù)處理文件。這允許你打包除 JavaScript 之外的任何靜態(tài)資源。
loader是webpack中一個非常核心的概念, loader有很多種, 不同的內(nèi)容需要使用不同的loader來加載.
2. loader的使用
我們首先來創(chuàng)建一個css文件, 然后將css文件引入到項(xiàng)目中
第一步: 創(chuàng)建main.css文件
body{ background-color: #085e7d; }
第二步: 將main.css文件引入到main.js中
require("./css/main.css")
這是使用commonJs的寫法引入的. 引入css以后, 不需要任何返回值, 所以, 我們可以不用寫成 "let 變量名 = require(文件路徑)"
第三步: 執(zhí)行npm run build, 會報異常
這個異常的意思是, 缺少合適的loader. 因?yàn)槲覀円肓薱ss, 但是還沒有引入解析css的loader.
css需要兩個loader :
- 一個是css-loader
- 另一個是style-loader
css-loader: 只負(fù)責(zé)加載css文件, style-loader: 負(fù)責(zé)將樣式加載到Dom中
第四步: 通過npm安裝loader
我們的目標(biāo)是安裝loader, 可以去官網(wǎng)找到對應(yīng)的loader. css文件對應(yīng)的loader.
官網(wǎng)地址: www.webpackjs.com
找到css-loader的用法
安裝命令
npm install --save-dev css-loader
第五步: 在webpack.config.js中的modules關(guān)鍵字下配置
module: { rules: [ { test: /\.css$/, use: ['css-loader'] } ] }
第六步: 安裝style-loader
安裝方法和css是一樣的. 可以通過查詢官網(wǎng)找到方法
安裝style-loader命令
npm install --save-dev style-loader
然后在將style-loader放在css-loader的前面
module: { rules: [ { test: /\.css$/, // css-loader: 只負(fù)責(zé)加載css文件 // style-loader: 負(fù)責(zé)將樣式加載到Dom中 // 注意: 使用loader加載的時候, 是從右向左加載的. 所以, 先加載css-loader, 在加載style-loader use: ['style-loader','css-loader' ] } ] }
為什么需要將style-loader放在前面呢?
其實(shí)在解析css的過程中, 先用到的是css-loader, 然后使用到的是style-loader. 但是webpack.config.js在解析的時候, 是從右往左解析的.
第七步: 打包
npm run build
打包以后報錯:
css (node:93638) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function
遇到這個問題, 說明版本不合適, 我們使用的webpack是3.6.0的版本, 打包的時候, 我們需要重新制定一下css-loader和style-loader的版本號
打開package.json, 找到devDependencies
"devDependencies": { "css-loader": "^2.1.1", "style-loader": "^2.0.0", "webpack": "^3.6.0", }
指定css-loader和style-loader的版本號分別是2.1.1和2.0.0
再次打包, 成功!
六. webpack打包less文件
其實(shí)我們知道如何打包c(diǎn)ss文件了, 那么打包less文件方法是類似的
第一步: 定義一個less文件
我們定義一個less文件, 起個名字common.less
@fontsize: 24px; @fontcolor: #5112b8; body { font-size: @fontsize; color: @fontcolor; }
第二步: 將less文件import引入到main.js中
require("./css/special.less")
第三步: 安裝less組件, 應(yīng)該安裝哪些組件呢? 可以看https://cn.vuejs.org/v2/guide/
查詢官網(wǎng): www.webpackjs.com
安裝組件命令
npm install --save-dev less-loader less
添加規(guī)則
module.exports = { ... module: { rules: [{ test: /\.less$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "less-loader" // compiles Less to CSS }] }] } };
注意: 順序不能改變
第四步: 重新打包.
npm run build
七. webpack打包圖片文件
下面來看看webapck是如何打包圖片的
第一步: 在css中引入一個圖片文件
比如: 我引入了一個背景圖
然后將圖片作為背景引入到main.css中
body{ background: url("../img/123.jpeg"); }
第二步: 將main.css文件通過import引入到main.js中
require("./css/main.less")
我們知道webpack是自動打包工具, 在打包main.js的時候, 他會看里面都引入了哪些內(nèi)容. 他發(fā)現(xiàn)引入了main.css, 就是去自動加載并解析css對應(yīng)的模塊. 在css中引入了圖片, 就會去自動加載并解析圖片對應(yīng)的模塊.
第三步: 安裝解析圖片的組件
查詢官網(wǎng): www.webpackjs.com
我們看到background是通過url引入的, 首先需要url-loader模塊.
安裝組件命令
npm install --save-dev url-loader
添加規(guī)則
{ test: /\.(png|jpg|gif|jpeg)$/, use: [ { loader: 'url-loader', options: { limit: 8000, } }] }
我們發(fā)現(xiàn)這次引入的時候有一個options參數(shù), 這個參數(shù)限制了圖片的大小.
注意:
- 當(dāng)加載的圖片, 小于limit時, 會將圖片編譯成base64字符串形式. --- 不需要文件, 因?yàn)樗且粋€base64字符串
- 當(dāng)加載的圖片, 大于limit是, 需要使用file-loader模塊來加載. --- 當(dāng)文件來處理, 就需要打包成文件, 需要file-loader
當(dāng)以文件的形式加載的時候, 需要指定一個打包路徑. 否則加載的文件目錄是根目錄, 結(jié)果會找不到文件, 因?yàn)槲覀兊奈募罱K打包到dist下面了.
module.exports={ // 入口 entry: "./src/main.js", output: { path: path.resolve(__dirname, 'dist'), filename: "bundle.js", publicPath:"dist/" } ... }
我們可以在output位置增加publicPath:"dist/" 以后, 所有的路徑類的文件在打包編譯的時候, 都會打包到這個路徑下面
八. webpack打包--將ES6打包成ES5
為什么需要將es6打包成es5呢? 因?yàn)樯鲜龇绞降膚ebpack打包后, 并沒有將ES6的語法轉(zhuǎn)換成ES5的, 比如:
這會有什么問題呢?
有些瀏覽器可能不認(rèn)識. 因?yàn)椴皇撬械臑g覽器都兼容ES6, 但基本所有的瀏覽器都兼容ES5的語法. 因此我們需要將ES6的語法轉(zhuǎn)換成ES5的語法
方法和上面是一樣的.
第一步: 安裝組件
打包ES6到ES5需要的組件是bebal
查詢官網(wǎng)需要安裝哪些組件: www.webpackjs.com
安裝命令:
npm install --save-dev babel-loader@7 babel-core babel-preset-es2015
我們這里安裝的是babel-loader的7的版本. babel-preset的版本是es2015
第二步: 配置babel-loader組件
module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['es2015'] } } } ] }
這個配置里面指定了exclude, 排除哪些目錄: 這里排除了node_modules目錄, 因?yàn)檫@個目錄下的文件我們不需要打包. 是node編譯需要的內(nèi)容.
presets屬性,用來指定將es6轉(zhuǎn)換成es5需要的版本. 我們這里直接填es2015就可以了.
第三步: 打包
npm run build
這次在去看bundle.js文件, 里面就沒有es6的語法了
【相關(guān)推薦:vuejs視頻教程、web前端開發(fā)】
The above is the detailed content of What files can vue webpack package?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

The core of the front-end routing system is to map URLs to components. VueRouter and ReactRouter realize refresh-free page switching by listening for URL changes and loading corresponding components. The configuration methods include: 1. Nested routing, allowing the nested child components in the parent component; 2. Dynamic routing, loading different components according to URL parameters; 3. Route guard, performing logic such as permission checks before and after route switching.

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

The core differences between Vue.js and React in component development are: 1) Vue.js uses template syntax and option API, while React uses JSX and functional components; 2) Vue.js uses responsive systems, React uses immutable data and virtual DOM; 3) Vue.js provides multiple life cycle hooks, while React uses more useEffect hooks.

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

When Vue.js handles array updates, the view is not updated because Object.defineProperty cannot directly listen to array changes. Solutions include: 1. Use the Vue.set method to modify the array index; 2. Reassign the entire array; 3. Use the rewritten mutation method of Vue to operate the array.

Methods to optimize the performance of large lists and complex components in Vue include: 1. Use the v-once directive to process static content to reduce unnecessary updates; 2. implement virtual scrolling and render only the content of the visual area, such as using the vue-virtual-scroller library; 3. Cache components through keep-alive or v-once to avoid duplicate mounts; 4. Use computed properties and listeners to optimize responsive logic to reduce the re-rendering range; 5. Follow best practices, such as using unique keys in v-for, avoiding inline functions in templates, and using performance analysis tools to locate bottlenecks. These strategies can effectively improve application fluency.

Usingthe:keyattributewithv-forinVueisessentialforperformanceandcorrectbehavior.First,ithelpsVuetrackeachelementefficientlybyenablingthevirtualDOMdiffingalgorithmtoidentifyandupdateonlywhat’snecessary.Second,itpreservescomponentstateinsideloops,ensuri
