文件加载器中的意外[路径] [英] Unexpected [path] in file-loader
问题描述
对于我的图像位置:/src/assets/bitmap/sample.jpg
给出关键配置:
context: resolve('src')
output: {
path: resolve('builds/web'),
publicPath: '',
filename: ifProd('[name].[chunkHash].js', '[name].js')
},
...
loaders: [
{
test: /\.(png|jpg|jpeg)/,
loader: 'file-loader?name=[path][name].[ext]?[hash]'
}
]
我期望图像的输出结构如下:
I am expecting output structure for the image that looks like this:
/builds/web/assets/bitmap/sample.jpg
相反,我得到了:
/builds/web/src/assets/bitmap/sample.jpg
如何告诉文件加载器输出路径必须相对于/src
而不是/
?
How do I tell the file-loader that output path needs to be relative to /src
and not /
?
推荐答案
经过2天的反复试验(感谢Webpack文档!),我发现有一种方法可以控制文件加载器的输出并复制文件加载器的文件结构. 输出目录中的源目录.这是Webpack设置context
,可用于每个加载程序和构建.
After 2 days of trial and error (Thanks Webpack docs!) I found out that there's a way to control file-loader's output and replicate the file structure of the source directory in the output directory. It's the Webpack setting context
, which can be used per loader as well as per build.
以下是文件加载器的示例:
Here's an example for file-loader:
use: [{
loader: 'file-loader',
options: {
context: <path>, // The directory to draw relative paths from
name: '[path][name].[ext]'
},
},
让我们更深入地研究它的工作原理.
Let's dive deeper into how it works.
假设我们正尝试通过www.website.com/assets/images/user.png
加载图像,而我们项目的文件结构为:
Say we're trying to load an image via www.website.com/assets/images/user.png
, and our project's file structure is:
project/
├── src/
│ └── assets/
│ └── images/
│ └── user.png
└── build/
所需的结果将是:
project/
├── src/
│ └── assets/
│ └── images/
│ └── user.png
└── build/
└── assets/
└── images/
└── user.png
此配置为:
use: [{
loader: 'file-loader',
options: {
context: path.resolve(__dirname, 'src')
name: '[path][name].[ext]'
},
},
那是因为您要复制build
文件夹内src
文件夹下的文件结构.
And that is because you want to replicate the file structure under src
folder inside the build
folder.
如果要从路径中删除assets
目录,则context
的值应为:path.resolve(__dirname, 'src/assets')
,并且文件加载器将复制以'src/assets'开头的相对路径,并且结果将是:
If you wanted to remove the assets
directory from the path, the value for context
would be: path.resolve(__dirname, 'src/assets')
, and file-loader will replicate the relative paths starting in 'src/assets' instead, and the result would be:
project/
├── src/
│ └── assets/
│ └── images/
│ └── user.png
└── build/
└── images/
└── user.png
这篇关于文件加载器中的意外[路径]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!