首頁  >  文章  >  web前端  >  webpack3的loader使用解析

webpack3的loader使用解析

php中世界最好的语言
php中世界最好的语言原創
2018-04-16 15:47:471272瀏覽

這次帶給大家webpack3的loader使用解析,webpack3中loader使用解析的注意事項有哪些,以下就是實戰案例,一起來看一下。

先亮出webpack官方網站,webpack能做什麼?官網給的答案就是,一句話,讓一切變得簡單!

各式各樣的loader層出不窮,讓我們在建置時不知所措,於此,總結下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 can transform files 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