Webpack is a tool that lets you compile JavaScript modules. It’s also known as a module bundler.
Webpack是使您可以編譯JavaScript模塊的工具。 也稱為模塊捆綁器 。
Given a large number of files, it generates a single file (or a few files) that run your app.
給定大量文件,它將生成一個(或幾個文件)運行您的應用程序的文件。
It can perform many operations:
它可以執行許多操作:
- helps you bundle your resources. 幫助您捆綁資源。
- watches for changes and re-runs the tasks. 監視更改并重新運行任務。
can run Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.
可以將Babel轉換運行到ES5,從而使您可以使用最新的JavaScript功能,而不必擔心瀏覽器支持。
- can transpile CoffeeScript to JavaScript 可以將CoffeeScript轉換為JavaScript
- can convert inline images to data URIs. 可以將嵌入式圖像轉換為數據URI。
- allows you to use require() for CSS files. 允許您將require()用于CSS文件。
- can run a development webserver. 可以運行開發Web服務器。
- can handle hot module replacement. 可以處理熱模塊更換。
- can split the output files into multiple files to avoid having a huge JS file to load in the first page hit. 可以將輸出文件分為多個文件,以避免在首頁命中時加載巨大的JS文件。
can perform tree shaking.
可以搖樹 。
Webpack is not limited to being used on the front-end, but is useful in backend Node.js development as well.
Webpack不僅限于在前端使用,在后端Node.js開發中也很有用。
There are many predecessors of Webpack and lots of similarities in what those tools and Webpack do. The main difference is that those tools are known as task runners, while Webpack was born as a module bundler.
Webpack的前身很多,并且這些工具和Webpack的功能有很多相似之處。 主要區別在于這些工具被稱為任務運行器 ,而Webpack則是模塊捆綁器。
Webpack is a more focused tool. You just need to specify an entry point to your app (it could even be an HTML file with script tags) and webpack analyzes the files and bundles them in a single JavaScript output file that includes everything you need to run the app.
Webpack是更集中的工具。 您只需要指定應用程序的入口點(它甚至可以是帶有腳本標簽HTML文件),然后webpack會分析這些文件并將它們捆綁在一個JavaScript輸出文件中,該文件包含您運行該應用程序所需的一切。
安裝Webpack (Installing Webpack)
Webpack can be installed globally or locally for each project.
Webpack可以在每個項目的全局或本地安裝。
全局安裝 (Global install)
Here’s how to install it globally with Yarn:
這是使用Yarn全局安裝的方法:
yarn global add webpack webpack-cli
with npm:
與npm :
npm i -g webpack webpack-cli
once this is done, you should be able to run
完成此操作后,您應該可以運行
webpack-cli
本地安裝 (Local Install)
Webpack can be installed locally as well. It’s the recommended setup, because Webpack can be updated per-project, and you have less resistance in using the latest features just for a small project rather than updating all the projects you have that use Webpack.
Webpack也可以在本地安裝。 這是推薦的設置,因為Webpack可以按項目進行更新,并且您對僅針對小型項目使用最新功能的阻力較小,而不必更新擁有Webpack的所有項目。
With Yarn:
帶紗 :
yarn add webpack webpack-cli -D
with npm:
與npm :
npm i webpack webpack-cli --save-dev
Once this is done, add this to your package.json
file:
完成后,將其添加到package.json
文件:
{ //... "scripts": { "build": "webpack" } }
Once this is done, you can run Webpack by typing
完成此操作后,您可以通過鍵入以下內容來運行Webpack:
yarn build
in the project root.
在項目根目錄中。
Webpack配置 (Webpack configuration)
By default, Webpack (starting from version 4) does not require any config if you respect these conventions:
默認情況下,如果遵守以下約定,Webpack(從版本4開始)不需要任何配置:
the entry point of your app is
./src/index.js
您的應用程序的入口點是
./src/index.js
the output is put in
./dist/main.js
.輸出放在
./dist/main.js
。- Webpack works in production mode Webpack在生產模式下工作
You can customize every little bit of Webpack of course, when you need. The Webpack configuration is stored in the webpack.config.js
file, in the project root folder.
當然,您可以根據需要自定義Webpack的每一個細節。 Webpack配置存儲在項目根文件夾中的webpack.config.js
文件中。
入口點 (The entry point)
By default the entry point is ./src/index.js
This simple example uses the ./index.js
file as a starting point:
默認情況下,入口點是./src/index.js
這個簡單的示例使用./index.js
文件作為起點:
module.exports = { /*...*/ entry: './index.js' /*...*/}
輸出 (The output)
By default the output is generated in ./dist/main.js
. This example puts the output bundle into app.js
:
默認情況下,輸出是在./dist/main.js
生成的。 此示例將輸出包放入app.js
:
module.exports = { /*...*/ output: { path: path.resolve(__dirname, 'dist'), filename: 'app.js' } /*...*/}
Using Webpack allows you to use import
or require
statements in your JavaScript code not just to include other JavaScript, but any kind of file (for example CSS).
使用Webpack允許您在JavaScript代碼中使用import
或require
語句,不僅包括其他JavaScript,還包括任何類型的文件(例如CSS)。
Webpack aims to handle all our dependencies, not just JavaScript, and loaders are one way to do that.
Webpack旨在處理我們所有的依賴關系,而不僅僅是JavaScript,而加載程序是做到這一點的一種方法。
For example, in your code you can use:
例如,在您的代碼中,您可以使用:
import 'style.css'
by using this loader configuration:
通過使用此加載程序配置:
module.exports = { /*...*/ module: { rules: [ { test: /\.css$/, use: 'css-loader' }, }] } /*...*/}
The regular expression targets any CSS file.
正則表達式以任何CSS文件為目標。
A loader can have options:
裝載機可以有以下選擇:
module.exports = { /*...*/ module: { rules: [ { test: /\.css$/, use: [ { loader: 'css-loader', options: { modules: true } } ] } ] } /*...*/}
You can require multiple loaders for each rule:
您可以為每個規則要求多個加載程序:
module.exports = { /*...*/ module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader', ] } ] } /*...*/}
In this example, css-loader
interprets the import 'style.css'
directive in the CSS. style-loader
is then responsible for injecting that CSS in the DOM, using a <sty
le> tag.
在此示例中, css-loader
解釋css-loader
import 'style.css'
指令。 然后, style-loader
負責使用<sty
le>標簽將CSS注入DOM中。
The order matters, and it’s reversed (the last is executed first).
順序很重要,并且順序相反(最后執行的是第一個)。
What kind of loaders are there? Many! You can find the full list here.
那里有什么裝載機? 許多! 您可以在此處找到完整列表 。
A commonly used loader is Babel, which is used to transpile modern JavaScript to ES5 code:
常用的加載器是Babel ,用于將現代JavaScript轉換為ES5代碼:
module.exports = { /*...*/ module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } /*...*/}
This example makes Babel preprocess all our React/JSX files:
這個例子使Babel預處理我們所有的React / JSX文件:
module.exports = { /*...*/ module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: 'babel-loader' } ] }, resolve: { extensions: [ '.js', '.jsx' ] } /*...*/}
See the babel-loader
options here.
在此處查看babel-loader
選項。
外掛程式 (Plugins)
Plugins are like loaders, but on steroids. They can do things that loaders can’t do, and they are the main building blocks of Webpack.
插件就像加載程序一樣,但是在類固醇上。 他們可以完成加載程序無法完成的工作,它們是Webpack的主要組成部分。
Take this example:
舉個例子:
module.exports = { /*...*/ plugins: [ new HTMLWebpackPlugin() ] /*...*/}
The HTMLWebpackPlugin
plugin does the job of automatically creating an HTML file and adding the output JS bundle path, so the JavaScript is ready to be served.
HTMLWebpackPlugin
插件可以自動創建HTML文件并添加輸出JS包路徑,因此可以隨時使用JavaScript。
There are lots of plugins available.
有很多可用的插件 。
One useful plugin, CleanWebpackPlugin
, can be used to clear the dist/
folder before creating any output, so you don’t leave files around when you change the names of the output files:
一個有用的插件CleanWebpackPlugin
可以用于在創建任何輸出之前清除dist/
文件夾,因此在更改輸出文件的名稱時,您不會留下文件:
module.exports = { /*...*/ plugins: [ new CleanWebpackPlugin(['dist']), ] /*...*/}
Webpack模式 (The Webpack mode)
This mode (introduced in Webpack 4) sets the environment on which Webpack works. It can be set to development
or production
(defaults to production, so you only set it when moving to development).
此模式(在Webpack 4中引入)設置了Webpack工作的環境。 可以將其設置為development
或production
(默認為生產,因此僅在進行開發時進行設置)。
module.exports = { entry: './index.js', mode: 'development', output: { path: path.resolve(__dirname, 'dist'), filename: 'app.js' }}
Development mode:
開發方式:
- builds very fast 建立非常快
- is less optimized than production 沒有比生產優化
- does not remove comments 不刪除評論
- provides more detailed error messages and suggestions 提供更詳細的錯誤消息和建議
- provides a better debugging experience 提供更好的調試體驗
Production mode is slower to build, since it needs to generate a more optimized bundle. The resulting JavaScript file is smaller in size, as it removes many things that are not needed in production.
生產模式的構建速度較慢,因為它需要生成更優化的捆綁包。 生成JavaScript文件較小,因為它刪除了生產中不需要的許多東西。
I made a sample app that just prints a console.log
statement.
我制作了一個示例應用程序,僅打印console.log
語句。
Here’s the production bundle:
這是產品包:
Here’s the development bundle:
這是開發包:
運行Webpack (Running Webpack)
Webpack can be run from the command line manually if installed globally. But generally you write a script inside the package.json
file, which is then run using npm
or yarn
.
如果Webpack已全局安裝,則可以從命令行手動運行。 但是通常您會在package.json
文件中編寫一個腳本,然后使用npm
或yarn
運行該腳本。
For example this package.json
scripts definition we used before:
例如,我們之前使用的以下package.json
腳本定義:
"scripts": { "build": "webpack"}
allows us to run webpack
by running
允許我們通過運行來運行webpack
npm run build
or
要么
yarn run build
or simply
或簡單地
yarn build
觀察變化 (Watching changes)
Webpack can automatically rebuild the bundle when a change in your app happens, and it keeps listening for the next change.
當您的應用程序發生更改時,Webpack可以自動重建捆綁包,并且它會一直在監聽下一個更改。
Just add this script:
只需添加以下腳本:
"scripts": { "watch": "webpack --watch"}
and run
并運行
npm run watch
or
要么
yarn run watch
or simply
或簡單地
yarn watch
One nice feature of the watch mode is that the bundle is only changed if the build has no errors. If there are errors, watch
will keep listening for changes, and try to rebuild the bundle, but the current, working bundle is not affected by those problematic builds.
監視模式的一個不錯的功能是,僅當構建沒有錯誤時才更改捆綁軟件。 如果有錯誤, watch
將繼續偵聽更改,并嘗試重建捆綁軟件,但是當前有效的捆綁軟件不受那些有問題的構建的影響。
處理圖像 (Handling images)
Webpack allows you to use images in a very convenient way, using the file-loader
loader.
Webpack允許您使用file-loader
器file-loader
器以非常方便的方式使用圖像。
This simple configuration:
這個簡單的配置:
module.exports = { /*...*/ module: { rules: [ { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] } ] } /*...*/}
Allows you to import images in your JavaScript:
允許您在JavaScript中導入圖像:
import Icon from './icon.png'const img = new Image()img.src = Iconelement.appendChild(img)
Where img
is an HTMLImageElement. Check out the Image docs.
其中img
是HTMLImageElement。 查看Image文檔 。
file-loader
can handle other asset types as well, like fonts, CSV files, XML, and more.
file-loader
還可以處理其他資產類型,例如字體,CSV文件,XML等。
Another nice tool to work with images is the url-loader
loader.
另一個處理圖像的好工具是url-loader
loader。
This example loads any PNG file smaller than 8KB as a data URL.
本示例將小于8KB的任何PNG文件加載為數據URL 。
module.exports = { /*...*/ module: { rules: [ { test: /\.png$/, use: [ { loader: 'url-loader', options: { limit: 8192 } } ] } ] } /*...*/}
處理您的SASS代碼并將其轉換為CSS (Process your SASS code and transform it to CSS)
Using sass-loader
, css-loader
and style-loader
:
使用sass-loader
, css-loader
和style-loader
:
module.exports = { /*...*/ module: { rules: [ { test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader' ] } ] } /*...*/}
生成源地圖 (Generate Source Maps)
Since Webpack bundles the code, Source Maps are mandatory to get a reference to the original file that raised an error. For example:
由于Webpack捆綁了代碼,因此必須使用“源映射”才能獲得對引發錯誤的原始文件的引用。 例如:
You tell Webpack to generate source maps using the devtool
property of the configuration:
您告訴Webpack使用配置的devtool
屬性生成源映射:
module.exports = { /*...*/ devtool: 'inline-source-map', /*...*/}
devtool
has many possible values, the most used probably are:
devtool
有許多可能的值 ,最常用的是:
none
: adds no source mapsnone
:不添加源地圖source-map
: ideal for production, provides a separate source map that can be minimized, and adds a reference into the bundle, so development tools know that the source map is available. Of course you should configure the server to avoid shipping this, and just use it for debugging purposessource-map
:非常適合生產,提供可以最小化的單獨的源映射,并在捆綁包中添加引用,因此開發工具知道該源映射可用。 當然,您應該配置服務器以避免運送它,而僅將其用于調試目的inline-source-map
: ideal for development, inlines the source map as a Data URLinline-source-map
:非常適合開發,將源映射作為數據URL內聯
I publish 1 free programming tutorial per day on flaviocopes.com, check it out!
我每天在flaviocopes.com上發布1個免費的編程教程,請查看!
Originally published at flaviocopes.com.
最初發布于flaviocopes.com 。
翻譯自: https://www.freecodecamp.org/news/a-beginners-introduction-to-webpack-2620415e46b3/