Webpack初學者介紹

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代碼中使用importrequire語句,不僅包括其他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 <style> 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工作的環境。 可以將其設置為developmentproduction (默認為生產,因此僅在進行開發時進行設置)。

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文件中編寫一個腳本,然后使用npmyarn運行該腳本。

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-loaderfile-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-loadercss-loaderstyle-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 maps

    none :不添加源地圖

  • 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 purposes

    source-map :非常適合生產,提供可以最小化的單獨的源映射,并在捆綁包中添加引用,因此開發工具知道該源映射可用。 當然,您應該配置服務器以避免運送它,而僅將其用于調試目的

  • inline-source-map: ideal for development, inlines the source map as a Data URL

    inline-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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393847.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393847.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393847.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Android Coding利器之掌握小技巧,助你Coding更上一層樓~

本文講的是Android Coding利器之掌握小技巧&#xff0c;助你Coding更上一層樓~&#xff0c;話說前幾天在網上瀏覽到一大牛寫的關于Android布局優化的文章&#xff0c;看后感觸很深&#xff0c;回過頭看看自己寫過的代碼&#xff0c;發現還是有不少需要改進&#xff0c;今天找不…

linux系統報警怎么辦,常見Linux系統故障和解決方法

常見Linux系統故障和解決方法發布時間&#xff1a;2020-06-06 14:48:19來源&#xff1a;億速云閱讀&#xff1a;212作者&#xff1a;Leah欄目&#xff1a;云計算這篇文章給大家分享的是常見的Linux系統故障和解決方法。在使用系統的過程中總會有各種各樣的故障&#xff0c;所以…

Vuex 模塊化與項目實例 (2.0)

Vuex 強調使用單一狀態樹&#xff0c;即在一個項目里只有一個 store&#xff0c;這個 store 集中管理了項目中所有的數據以及對數據的操作行為。但是這樣帶來的問題是 store 可能會非常臃腫龐大不易維護&#xff0c;所以就需要對狀態樹進行模塊化的拆分。 首先貼出一個邏輯比較…

click js自動點擊 vue_vue.js2.0點擊獲取自己的屬性和jquery方法

如下所示&#xff1a;:data-index"index":dt"index"v-on:click"onclick($event,index)":data-d "JSON.stringify( item)"href"http://www.baidu.com" rel"external nofollow" rel"external nofollow"da…

Python:知識目錄

Python目錄 第一篇&#xff1a;數據類型部分文件操作 基礎數據類型---str 基礎數據類型---List 基礎數據類型---dict 基礎數據類型---set 基礎數據類型---bytes 數據類型的總結 文件操作------讀&#xff0c;寫 文件操作------使用方法 第二章&#xff1a;函數模塊 初識函數…

初學者css常見問題_5分鐘內學習CSS-初學者教程

初學者css常見問題關于網絡設計語言的快速教程。 (A quick tutorial on the design language of the web.) CSS (Cascading Style Sheets) is what makes web pages look good and presentable. It’s an essential part of modern web development and a must-have skill for …

leetcode39. 組合總和(回溯)

給定一個無重復元素的數組 candidates 和一個目標數 target &#xff0c;找出 candidates 中所有可以使數字和為 target 的組合。 candidates 中的數字可以無限制重復被選取。 說明&#xff1a; 所有數字&#xff08;包括 target&#xff09;都是正整數。 解集不能包含重復的…

一臉懵逼學習基于CentOs的Hadoop集群安裝與配置(三臺機器跑集群)

1&#xff1a;Hadoop分布式計算平臺是由Apache軟件基金會開發的一個開源分布式計算平臺。以Hadoop分布式文件系統&#xff08;HDFS&#xff09;和MapReduce&#xff08;Google MapReduce的開源實現&#xff09;為核心的Hadoop為用戶提供了系統底層細節透明的分布式基礎架構。 注…

linux批量去掉文件名前綴,linux 批量刪除某個前綴文件

1. 命令 (參考&#xff1a;https://blog.csdn.net/kl28978113/article/details/80271831)find ./ -name updatesites*-* -exec rm {} \;2. 舉例[rootadmin batch-create-sites]# ls2020-02-13-10-10.out logs-2020-04-07-08-00.out updatesites-2020-02-12-01-49-25.xlsx updat…

Docker - 避免啟動container后運行shell腳本執行完成后docker退出container

問題 最近在使用 Dockerfile 啟動容器&#xff0c;發現使用Dockerfile調用容器里面的shell&#xff0c;當shell執行完成以后&#xff0c;docker會退出容器。 分析 Docker 在執行shell的時候&#xff0c;是在后臺執行的&#xff1b;因此&#xff0c;在shell執行完成以后&#xf…

css畫橫線箭頭_用CSS繪制三角形箭頭

用CSS繪制三角形箭頭。使用純CSS&#xff0c;你只需要很少的代碼就可以創作出各種瀏覽器都兼容的三角形箭頭&#xff01;CSS代碼:/* create an arrow that points up */div.arrow-up {width: 0;height: 0;border-left: 5px solid transparent; /* left arrow slant */border-ri…

Jmeter參數化的理解

jmeter參數化有兩種情況&#xff1a; jmeter執行的sql語句中值的參數化&#xff08;如select過濾條件&#xff09;csv data set config參數表示方式${zjhm}jmx腳本的設置屬性參數化&#xff0c;方便命令行調用時修改參數&#xff08;如并發量、執行時間&#xff09;在腳本中調用…

leetcode216. 組合總和 III(回溯)

找出所有相加之和為 n 的 k 個數的組合。組合中只允許含有 1 - 9 的正整數&#xff0c;并且每種組合中不存在重復的數字。 說明&#xff1a; 所有數字都是正整數。 解集不能包含重復的組合。 示例 1: 輸入: k 3, n 7 輸出: [[1,2,4]] 代碼 class Solution {List<List…

linux內核epub,Android底層開發技術實戰詳解——內核、移植和驅動(第2版)[EPUB][MOBI][AZW3][42.33MB]...

內容簡介本書從底層原理開始講起&#xff0c;結合真實的案例向讀者詳細介紹了Android內核、移植和驅動開發的整個流程。全書分為21章&#xff0c;依次講解驅動移植的必要性&#xff0c; Goldfish、OMAP內核和驅動解析&#xff0c;顯示系統、輸入系統、振動器系統、音頻系統、視…

機器學習崗位太少_太多的東西要學習,很少的時間

機器學習崗位太少by Rick West由里克韋斯特(Rick West) 太多的東西要學習&#xff0c;很少的時間 (So much to learn, so little time) 我學習&#xff0c;保持動力并實現目標的主要技巧 (My top tips for learning, staying motivated, and achieving your goals) One of the…

用9種辦法解決 JS 閉包經典面試題之 for 循環取 i

2017-01-06Tomson JavaScript轉自 https://segmentfault.com/a/1190000003818163 閉包 1.正確的說,應該是指一個閉包域,每當聲明了一個函數,它就產生了一個閉包域(可以解釋為每個函數都有自己的函數棧),每個閉包域(Function 對象)都有一個 function scope(不是屬性),function s…

bzoj 2296: 【POJ Challenge】隨機種子

Time Limit: 1 Sec Memory Limit: 128 MBSec Special JudgeDescription1tthinking除了隨機算法&#xff0c;其他什么都不會。但是他還是可以ac很多題目&#xff0c;他用的是什么呢&#xff1f;他會選擇一個好的隨機種子&#xff0c;然后輸出答案。往往他選擇的一個好的種子可…

英特爾第十代處理器為什么不支持win7_5GHz動力澎湃 高主頻多核處理器成就巔峰玩家...

頻率之爭永遠是處理器領域無法回避的話題。高主頻在游戲中所帶來的高速運行&#xff0c;穩定幀數等特性永遠是玩家們所追求的目標。隨著英特爾第十代桌面及移動版酷睿處理器的發布&#xff0c;無論是臺式整機或是筆記本平臺&#xff0c;都已全面進入了5GHz時代。選擇英特爾處理…

leetcode46. 全排列(回溯)

給定一個 沒有重復 數字的序列&#xff0c;返回其所有可能的全排列。 示例: 輸入: [1,2,3] 輸出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 代碼 class Solution {List<List<Integer>> cListnew ArrayList<>();public List<List<…

初級算法-12.反轉字符串

題目描述: 編寫一個函數&#xff0c;其作用是將輸入的字符串反轉過來。輸入字符串以字符數組 char[] 的形式給出。 不要給另外的數組分配額外的空間&#xff0c;你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。 你可以假設數組中的所有字符都是 ASCII 碼表中的可打…