Instructs webpack to emit the required object as file and to return its public URL
npm install --save-dev file-loader
默认情况下,生成的文件的文件名就是文件内容的 MD5 哈希值并会保留所引用资源的原始扩展名。
import img from './file.png'
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
}
}
生成文件 file.png,输出到输出目录并返回 public URL。
"/public/path/0dcbbaa7013869e351f.png"
name
{String|Function}
[hash].[ext]
outputPath
{String|Function}
'undefined'
output
输出目录
useRelativePath
{Boolean}
false
context
时,应该将其设置为 true
emitFile
{Boolean}
true
##
You can configure a custom filename template for your file using the query parameter name
. For instance, to copy a file from your context
directory into the output directory retaining the full directory structure, you might use
{String}
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
{Function}
webpack.config.js
{
loader: 'file-loader',
options: {
name (file) {
if (env === 'development') {
return '[path][name].[ext]'
}
return '[hash].[ext]'
}
}
}
placeholders
[ext]
{String}
file.extname
[name]
{String}
file.basename
[path]
{String}
file.dirname
context
的路径
[hash]
{String}
md5
[N]
{Number}
regExp
匹配后获得到第 N 个匹配结果
hashes
[<hashType>:hash:<digestType>:<length>]
optionally you can configure
hashType
{String}
md5
sha1
, md5
, sha256
, sha512
digestType
{String}
base64
hex
, base26
, base32
, base36
, base49
, base52
, base58
, base62
, base64
length
{Number}
9999
默认情况下,文件会按照你指定的路径和名称输出同一目录中,且会使用相同的 URL 路径来访问文件。
context
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
context: ''
}
}
你可以使用 outputPath
,useRelativePath
和 publicPath
来指定自定义 output
输出路径和 public
发布目录。
publicPath
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
publicPath: 'assets/'
}
}
outputPath
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'images/'
}
}
useRelativePath
如果你希望为每个文件生成一个相对 URL 的 context
时,应该将 useRelativePath
设置为 true
。
{
loader: 'file-loader',
options: {
useRelativePath: process.env.NODE_ENV === "production"
}
}
emitFile
默认情况下会生成文件,可以通过将此项设置为 false 来禁用(例如使用了服务端的 packages)。
import img from './file.png'
{
loader: 'file-loader',
options: {
emitFile: false
}
}
⚠️ 返回 public URL 但不会生成文件
`${publicPath}/0dcbbaa701328e351f.png`
import png from 'image.png'
webpack.config.js
{
loader: 'file-loader',
options: {
name: 'dirname/[hash].[ext]'
}
}
dirname/0dcbbaa701328ae351f.png
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[sha512:hash:base64:7].[ext]'
}
}
gdyb21L.png
import png from 'path/to/file.png'
webpack.config.js
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]?[hash]'
}
}
path/to/file.png?e43b20c069c4a01867c31e98cbce33c9
|
|
|
|