File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments