一张图带你了解webpack的require.context

一张图带你了解webpack的require.context

很多人应该像我一样,对于webpackrequire.context都是一知半解吧。网上很多关于require.context的使用案例,但是我没找到可以帮助我理解这个知识点的,于是也决定自己来探索一下。下面以网上流行的svg图标方案为例说明。对了,本文的重点是require.context,并不会去解释svg symbol方案svg-sprite-loader

关键代码

关键代码

src/icons/index.js

1
2
3
const context = require.context("./svg", true, /\.svg$/)

context.keys().map(context)

main.js

1
import '@/icons'

webpack.base.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
test: /\.svg$/,
loader: "svg-sprite-loader",
include: [resolve("src/icons")],
options: {
symbolId: "icon-[name]"
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: "url-loader",
exclude: [resolve("src/icons")],
options: {
limit: 10000,
name: utils.assetsPath("img/[name].[hash:7].[ext]")
}
},

why?

很多人跟我一样,一开始只想说,为什么这样就可以,why???

要知道是什么,就上打印大法。

1
2
3
4
5
const context = require.context("./svg", true, /\.svg$/)
// 看看你是何方神圣
console.log(context)

context.keys().map(context)

下面就真的以一张图进行解释,有问题的欢迎留言交流呀!

一张图说明


扫一扫下方小程序码或搜索Tusi博客,即刻阅读最新文章!

Tusi博客

You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×