搜尋
首頁web前端html教學Webpack基本用法_html/css_WEB-ITnose

 

本篇体验Webpack的基本面以及一个例子。

■ What is Webpack

 

● module bundler
● module with dependencies
● module generates static assets

 

■ Why Webpack

 

● good for development but also the user experience
● loaded on demand
● cache friendly
● webpack plugins can be injected into into the build process

 

■ 首次使用Webpack, 用CLI, 即Command Line Interface

 

→ 确认是否安装了NodeJS
npm -v
→ 安装 Webpack
npm install webpack -g
→ 创建一个简单的网站
.....webpacktest/
..........app.js
..........index.html
→ 导航到webpacktest所在文件夹
→ 对app.js文件使用webpack
webpack ./app.js bundle.js
→ 我们看到在webpacktest目录下多了一个bundle.js文件
→ 现在,可以在index.html中引用bundle.js文件,而不是app.js文件


■ 在项目中添加配置文件

 

→ 在项目根目录下创建名称为webpack.config.js文件
当设置好webpack.config.js文件后,每次我们导航到项目,只要使用webpack这一个命令就可以使用各项功能了。
module.exports = {
entry: "./app.js",
output: {
filename: "bundle.js"
}
}
→ 命令行来到需要Webpack的网站下
→ 直接输入webpack命令
webpack

 

■ 启用Webpack观察者模式

 

当webpack.config.js的配置发生变化,如果每次都要手动输入webpack命令来生成js文件的话,显得相对麻烦一些。Webpack为我们提供了观察者模式,启用后,任何的webpack.config.js中的变化将接受观察,自动生成最终的js文件。

 

→ 命令行来到需要Webpack的网站下
→ 启用观察者模式
webpack --watch
→ 在webpack.config.js中添加watch字段,并设置成true
module.exports = {
entry: "./app.js",
output: {
filename: "bundle.js"
},
watch: true
}
→ 这样,每次修改保存webpack.config.js中引用文件,bundle.js的文件会自动更新。


■ 安装启用Webpack DevServer

 

→ 导航到目标网站目录
→ 输入npm命令安装Webpack DevServer
npm install webpack-dev-server -g
→ 输入webpack-dev-server命令
webpack-dev-server
→ 看到大致如下内容
http://localhost:8080/webpack-dev-server
webpack result is served from /
cotent is served from D:\...
Hash:...
Version:webpack1.12.4
Time:94ms
...
webpack: bundle is now VALID.
→ 在浏览器中输入:http://localhost:8080/webpack-dev-server/
同时显示app.js文件中console.log和document.write的内容。
→ 修改webpack.config.js中依赖的文件并保存,浏览器中的内容就会自动更新

→ 如果不想显示console.log内容呢?
→ 在浏览器中输入:http://localhost:8080/
→ 此时,再修改webpack.config.js中依赖的文件并保存,浏览器的内容却不会更新?
→ 再次回到命令行,加入一个inline的flag
webpack-dev-server --inline
→ 此时,如果修改webpack.config.js中依赖的文件并保存,浏览器中的内容就会自动更新了☺

 

■ Bundling多个文件

 

→ 在项目下再添加一个login.js文件
console.log('login loaded');
→ app.js中引用login.js文件
require('./login');

document.write("Welcome to Big Hair Concerts!!Baby");
console.log('App loaded');
→ 在浏览器中输入:http://localhost:8080/
可以看到变化。
→ 在项目下再添加一个utils.js文件
console.log('logging from the utils.js file...');
→ 来到webpack.config.js下配置如下:
module.exports = {
entry: ["./utils","./app.js"],
output: {
filename: "bundle.js"
},
watch: true
}
→ 命令行导航到当前项目下
→ 重新启用Webpack DevServer
webpack-dev-server
→ 在http://localhost:8080/中体现了相应的变化


■ 一个例子

 

→ 创建一个名称为demo的文件夹

→ 命令行导航到demo文件夹

→ 创建package.json文件

npm init
然后在命令窗口输入各种信息或直接按Enter键确认,直至最终在demo下创建了package.json文件。

{
"name": "demo",
"version": "1.0.0",
"description": "some description about demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Darren",
"license": "ISC"
}


→ 为当前demo项目创建webpack

npm intall webpack --save-dev

运行成功后

● 在demo文件夹下多了node_modules文件夹
● 在package.json中多了有关webpack的配置

{
"name": "demo",
"version": "1.0.0",
"description": "some description about demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Darren",
"license": "ISC",
"devDependencies": {
"webpack": "^1.12.5"
}
}

现在,就可以在当前的demo项目下,在命令行窗口中运用各种命令了。


→ 输入如下命令查看webpack的命令语法

webpack -h

→ 在demo下创建webpack.config.js文件

module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js'
}
};

→ 在demo下创建main.js

document.write("Webpack for the win!");

→ 在demo下运行webpack命令

webpack

运行成功,在demo下多了一个bundle.js文件。

→ 在demo下添加index.html






Webpack Demo



→ 在demo下创建second.js

module.exports = document.write("Oh yeah another file");

→ 在main.js中引用second.js文件

require('./second.js');
document.write("Webpack for the win!");

→ 在当前demo项目下使用webpack命令

webpack

发现second.js文件已被引用到bundle.js文件中了。

→ 在当前demo项目下使用webpack -p命令

webpack -p

这样,bundle.js文件的内容呈压缩状态。

→ 为当前项目添加loader

各种loader在这里:http://webpack.github.io/docs/list-of-loaders.html

比如添加一个CoffeeScript loader

npm install coffee-loader --save-dev

运行成功后。

● 在node_modules文件夹下多了一个coffee-loader子文件夹。
● 在package.json中多了与coffee-loader相关的配置

{
"name": "demo",
"version": "1.0.0",
"description": "some description about demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Darren",
"license": "ISC",
"devDependencies": {
"coffee-loader": "^0.7.2",
"coffee-script": "^1.10.0",
"webpack": "^1.12.5"
}
}

● 在webpack.config.js中添加coffee-loader相关

module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.coffee$/, loader: "coffee-loader" }
]
}
};

在demo下添加third.coffee文件。

alert "webpack is boss!"

在main.js中引用third.coffee文件。

require('./second.js');
require("./third.coffee");
document.write("Webpack for the win!");

运行webpack命令,在bundle.js中多了与third.coffee文件相关的内容。

→ 添加CSS和图片

命令行导航到demo文件夹下,运行如下:

npm install style-loader css-loader url-loader --save-dev

运行成功后,在node_modules中多了css-loader, style-loader,在package.json中也多了相关配置:

{
"name": "demo",
"version": "1.0.0",
"description": "some description about demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Darren",
"license": "ISC",
"devDependencies": {
"coffee-loader": "^0.7.2",
"coffee-script": "^1.10.0",
"css-loader": "^0.22.0",
"style-loader": "^0.13.0",
"webpack": "^1.12.5"
}
}

在webpack.config.js中添加如下配置:

module.exports = {
entry: './main.js',
output: {
path: './build', // This is where images AND js will go
publicPath: 'http://yoururl.com/', // This is used to generate URLs
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.coffee$/, loader: "coffee-loader" },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'}
]
}
};

注意,在output中,把build用来存放生成的bundle.js和图片文件。publicPath用来存放网站地址。

修改index.html文件中的引用路径。






Webpack Demo




在demo下添加image.coffee文件。

img1 = document.createElement("img")
img1.src = require("./your-small-image.png")
document.body.appendChild img1

img2 = document.createElement("img")
img2.src = require("./your-big-image.png")
document.body.appendChild img2

在main.js中添加require("./image.coffee")

require('./second.js');
require("./third.coffee");
require("./image.coffee");
document.write("Webpack for the win!");


在demo下创建styles.css文件。

body {
background: tomato;
}

在main.js中添加require("./styles.css")

require('./second.js');
require("./third.coffee");
require("./image.coffee");
require("./styles.css")
document.write("Webpack for the win!");

运行webpack命令。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
HTML的角色:構建Web內容HTML的角色:構建Web內容Apr 11, 2025 am 12:12 AM

HTML的作用是通過標籤和屬性定義網頁的結構和內容。 1.HTML通過到、等標籤組織內容,使其易於閱讀和理解。 2.使用語義化標籤如、等增強可訪問性和SEO。 3.優化HTML代碼可以提高網頁加載速度和用戶體驗。

HTML和代碼:仔細觀察術語HTML和代碼:仔細觀察術語Apr 10, 2025 am 09:28 AM

htmlisaspecifictypefodyfocusedonstructuringwebcontent,而“代碼” badlyLyCludEslanguagesLikeLikejavascriptandPytyPythonForFunctionality.1)htmldefineswebpagertuctureduseTags.2)“代碼”代碼“ code” code code code codeSpassSesseseseseseseseAwiderRangeLangeLangeforLageforLogageforLogicIctInterract

HTML,CSS和JavaScript:Web開發人員的基本工具HTML,CSS和JavaScript:Web開發人員的基本工具Apr 09, 2025 am 12:12 AM

HTML、CSS和JavaScript是Web開發的三大支柱。 1.HTML定義網頁結構,使用標籤如、等。 2.CSS控製網頁樣式,使用選擇器和屬性如color、font-size等。 3.JavaScript實現動態效果和交互,通過事件監聽和DOM操作。

HTML,CSS和JavaScript的角色:核心職責HTML,CSS和JavaScript的角色:核心職責Apr 08, 2025 pm 07:05 PM

HTML定義網頁結構,CSS負責樣式和佈局,JavaScript賦予動態交互。三者在網頁開發中各司其職,共同構建豐富多彩的網站。

HTML容易為初學者學習嗎?HTML容易為初學者學習嗎?Apr 07, 2025 am 12:11 AM

HTML適合初學者學習,因為它簡單易學且能快速看到成果。 1)HTML的學習曲線平緩,易於上手。 2)只需掌握基本標籤即可開始創建網頁。 3)靈活性高,可與CSS和JavaScript結合使用。 4)豐富的學習資源和現代工具支持學習過程。

HTML中起始標籤的示例是什麼?HTML中起始標籤的示例是什麼?Apr 06, 2025 am 12:04 AM

AnexampleOfAstartingTaginHtmlis,beginSaparagraph.startingTagSareEssentialInhtmlastheyInitiateEllements,defiteTheeTheErtypes,andarecrucialforsstructuringwebpages wepages webpages andConstructingthedom。

如何利用CSS的Flexbox佈局實現菜單中虛線分割效果的居中對齊?如何利用CSS的Flexbox佈局實現菜單中虛線分割效果的居中對齊?Apr 05, 2025 pm 01:24 PM

如何設計菜單中的虛線分割效果?在設計菜單時,菜名和價格的左右對齊通常不難實現,但中間的虛線或點如何...

在線代碼編輯器究竟用什麼HTML元素實現代碼輸入?在線代碼編輯器究竟用什麼HTML元素實現代碼輸入?Apr 05, 2025 pm 01:21 PM

網頁代碼編輯器中的HTML元素分析許多在線代碼編輯器允許用戶輸入HTML、CSS和JavaScript代碼。最近,有人提出了一...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!