概述
- webpack的使用中我們會遇到各種各樣的插件、loader,
- webpack的功力主要體現在能理解各個插件、loader的數量上,理解的越多功力越深
- loader是什么呢?
背景
了解loader前,我們在來看個問題,有了前面的基礎我們還是用個簡單的樣例來說明
由于一切都是模塊,我們想用js import的方式統一加載css資源
//main.js
import "./main.css";
window.addEventListener("load", function () {});
//main.css
body {
color: aquamarine;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
<h1>Hello webpack splitchunks</h1>
<button id="btn1">頁面1</button>
<button id="btn2">頁面2</button>
</body>
</html>
嗯,如果能這樣加載就好了,我就不需要在寫<style>、<link>標記了,那么是不是這么寫呢
好,我們來試一下
//index.js
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const config = {
context: path.resolve(__dirname),
mode: "production",
optimization: {
minimize: false,
},
entry: "./main.js",
target: ["web", "es5"],
output: {
clean: true,
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
],
};
const compiler = webpack(config);
compiler.run((err, stats) => {
console.log(err);
let result = stats.toJson({
files: true,
assets: true,
chunk: true,
module: true,
entries: true,
})
debugger
});
看下結果,有個錯誤,
moduleName:'./main.css'
'Module parse failed: Unexpected token (1:5)\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

這里正是提示我們css檔案不能用import的方式加載,想要加載css檔案,你就需要loader
開始
先裝2個loader
npm install --save-dev css-loader style-loader
添加loader配置
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const config = {
context: path.resolve(__dirname),
mode: "production",
optimization: {
minimize: false,
},
entry: "./main.js",
target: ["web", "es5"],
output: {
clean: true,
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
const compiler = webpack(config);
compiler.run((err, stats) => {
console.log(err);
let result = stats.toJson({
files: true,
assets: true,
chunk: true,
module: true,
entries: true,
})
debugger
});
執行后沒有了錯誤,頁面也正常顯示了

看下生成了什么代碼(代碼太多,截取一部分)


css檔案居然被轉換成了字串,而且運行時會自動添加到<style>標記中
總結
- loader 可以讓webpack處理更多,更豐富的檔案型別,即使這個檔案并不是js檔案
- 有了loader的設計,webpack的應用場景強了,
- css-loader正是將我們的css檔案轉成了javastript的字串
- style-loader 則幫助我們將生成的樣式字串添加的
<style>標記中,他倆配合的也真是挺到位, - loader的設計并不局限于樣式的這個場景,理解這兩個loader可以讓我們更深入的理解loader的設計,比如如果我想把es6語法的js檔案都轉成es5的js運行時,是不是也可以呢?
- loader參考:https://webpack.docschina.org/loaders/css-loader
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/509638.html
標籤:其他
上一篇:Vue原始碼剖析
