Update (webpack-dev-server 4)
Since the latest version. You have to replace contentBasePublicPath
and contentBase
(see original solution below) with static.directory
and static.publicPath
. The feature still works.
webpack.config.js
{
devServer: {
static: {
directory: path.resolve(__dirname, './assets'),
publicPath: '/assets'
}
}
}
Tested with webpack 5.58.2
, webpack-cli 4.9.0
, webpack-dev-server 4.3.1
.
Keep reading the Original solution for further information.
Original (webpack-dev-server 3)
For everyone who wants real static files without copying them and landed here. The Webpack output configuration publicPath
does not work.
You need the DevServer property contentBase
and optional contentBasePublicPath
.
The documentation really lacks on these properties. So let me explain:
Use case: You want to use static files like videos, sounds and images without copying them.
In this example create a folder assets
in your project root directory. The rest configuration is default (src, dist).
webpack.config.js
{
devServer: {
contentBase: path.resolve(__dirname, './assets'),
contentBasePublicPath: '/assets'
}
}
Without contentBasePublicPath
the assets are accessible with root URL. Since contentBase
only defines the folder content.
Example:
Place an image file "test.png" into your assets folder.
Without contentBasePublicPath
you can access it with e.g. <img src="test.png">
. With contentBasePublicPath
you can use <img src="assets/test.png">
.
your-project
|- assets
| |- test.png
|- dist (...)
|- src (...)
You can use any path you want. E.g. move the assets to your src folder. Just place all assets here. It will not be processed / touched by the build. And the app is still loading from the default root (dist) path. This is what we want. The simplest and best solution in my opinion.
Tested with a TypeScript project and Webpack 5 (webpack-cli 4, webpack-dev-server 3).