Skip to content

Commit 6497dd5

Browse files
authored
Merge pull request #492 from rafaelrinaldi/develop
Add docs about `publicPath`
2 parents 048be25 + 16aef0e commit 6497dd5

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

content/guides/public-path.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
title: Public Path
3+
sort: 14
4+
contributors:
5+
- rafaelrinaldi
6+
---
7+
8+
Webpack has a very useful configuration that let you specify the base path for
9+
all the assets on your application. It's called `publicPath`.
10+
11+
## Use cases
12+
13+
There are a few use cases on real applications where this feature becomes
14+
specially neat.
15+
16+
### Set value on build time
17+
18+
For development mode what we usually have is an `assets/` folder that lives on
19+
the same level of our index page. This is fine but let's say you want to host
20+
all these static assets on a CDN on your production environment?
21+
22+
To approach this problem you can easily use a good old environment variable.
23+
Let's say we have a variable `ASSET_PATH`:
24+
25+
```js
26+
import webpack from 'webpack';
27+
28+
// Whatever comes as an environment variable, otherwise use root
29+
const ASSET_PATH = process.env.ASSET_PATH || '/';
30+
31+
export default {
32+
output: {
33+
publicPath: ASSET_PATH
34+
},
35+
36+
plugins: [
37+
// This makes it possible for us to safely use env vars on our code
38+
new webpack.DefinePlugin({
39+
'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH)
40+
})
41+
]
42+
};
43+
```
44+
45+
### Set value on the fly
46+
47+
Another possible use case is to set the public path on the fly. Webpack exposes
48+
a global variable that let's you do that, it's called `__webpack_public_path__`.
49+
So in your application entry point, you can simply do this:
50+
51+
```js
52+
__webpack_public_path__ = process.env.ASSET_PATH;
53+
```
54+
55+
That's all you need. Since we're already using the `DefinePlugin` on our
56+
configuration, `process.env.ASSET_PATH` will always be defined so we can safely
57+
do that.

0 commit comments

Comments
 (0)