For my image location: /src/assets/bitmap/sample.jpg
Given are the key configurations:
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
Instead, I get this:
/builds/web/src/assets/bitmap/sample.jpg
How do I tell the file-loader that output path needs to be relative to /src
and not /
?
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.
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/
The desired result would be:
project/
├── src/
│ └── assets/
│ └── images/
│ └── user.png
└── build/
└── assets/
└── images/
└── user.png
The configuration for this is:
use: [{
loader: 'file-loader',
options: {
context: path.resolve(__dirname, 'src')
name: '[path][name].[ext]'
},
},
And that is because you want to replicate the file structure under src
folder inside the build
folder.
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
来源:https://stackoverflow.com/questions/40580968/unexpected-path-in-file-loader