首頁 > web前端 > js教程 > 主體

webpack3之loader解析

小云云
發布: 2018-01-02 14:08:43
原創
1805 人瀏覽過

webpack能幹什麼?官網給的答案就是,一句話,讓一切變得簡單!各式各樣的loader層出不窮,讓我們在建置時不知所措,於此,總結下loader的全解析。本文主要介紹webpack3之loader全解析,小編覺得蠻不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

概念

loader,顧名思義,載入器,英文的解釋如下:

Loaders are transformations that are applied on the source code of a module . They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle front-end build steps. Loaders canle frontps. from a different language (like TypeScript) to JavaScript, or inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!

中文翻譯過來就是:

loader 用於對模組的原始碼進行轉換。 loader 可以讓你在 import 或「載入」模組時預處理檔案。因此,loader 類似於其他建置工具中“任務(task)”,並提供了處理前端建置步驟的強大方法。 loader 可以將檔案從不同的語言(如 TypeScript)轉換為 JavaScript,或將內嵌圖像轉換為 data URL。 loader 甚至允許你直接在 JavaScript 模組中 import CSS檔!

從中,可以看出loader的強大作用,分析下:

  1. #轉換的作用。開發所用到的都轉換成網頁載入所必備的html+css+js+img等要求格式的檔案。

  2. 轉換物件是原始碼。 loader只對原始碼轉換,至於其他的功能,plugins就來接收它做不到的地方。

總結一句話:loader, 載入的機器,形象的比喻下,就像一個豆漿機,放上你的原料,它就開始認真的工作了!

常用的loader

1、babel-loader

This package allows transpiling JavaScript files using Babel and webpack.

載入ES2015+ 程式碼,然後使用Babel 轉譯為ES5

安裝:


npm install --save-dev babel-loader babel-core babel-preset-env webpack
登入後複製

使用:


{
 test: /\.js$/,
 exclude: /node_modules/,
 loader: 'babel-loader'
}
登入後複製

2、style-loader

Adds CSS to the DOM by injecting a