Unexpected [path] in file-loader

梦想与她 提交于 2019-12-05 09:56:26

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!