I am currently working on a web application using React, TypeScript and Webpack. I want Webpack to generate images URLs according to a subdomain that I only know on runtime and not during the compile time.
I've read this on Webpacks's documentation: http://webpack.github.io/docs/configuration.html#output-publicpath
Note: In cases when the eventual publicPath of of output files isn’t known at compile time, it can be left blank and set dynamically at runtime in the entry point file. If you don’t know the publicPath while compiling you can omit it and set webpack_public_path on your entry point.
webpack_public_path = myRuntimePublicPath
// rest of your application entry
But I can't get it working.
I've set the webpack_public_path
variable in my app entry point. But how can I use its value in my Webpack config?
I need to use it here:
"module": { "rules": [ { "test": /.(png|jpg|gif)(\?[\s\S]+)?$/, "loaders": [
url?limit=8192&name=/images/[hash].[ext]
] } ] }
I need to do something like this:
"loaders": ['url?limit=8192&name=__webpack_public_path__/images/[hash].[ext]']
I've managed to make it work. So in my entry point file (start.tsx), I declare de __webpack_public_path__
free var before the imports and I assign its value after the imports.
/// <reference path="./definitions/definitions.d.ts" />
declare let __webpack_public_path__;
import './styles/main.scss';
/* tslint:disable:no-unused-variable */
import * as React from 'react';
/* tslint:enable:no-unused-variable */
import * as ReactDOM from 'react-dom';
import * as Redux from 'redux';
import { Root } from './components/root';
__webpack_public_path__ = `/xxxx/dist/`;
Now, the public path is being used when I have an img
tag:
<img src={require('../../images/logo.png')} />
Turns into:
<img src='/xxxx/dist/images/125665qsd64134fqsf.png')} />
Here's my basic setup in terms of the generated HTML:
<script>
window.resourceBaseUrl = 'server-generated-path';
</script>
<script src="path-to-bundle" charset="utf-8"></script>
My main entry point script:
__webpack_public_path__ = window.resourceBaseUrl;