Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Webpack, how do I set the public path dynamically?

I am using Angular2/Typescript/Webpack to build an application

I'm having problem setting the Webpack option publicPath dynamically. In the official Webpack docs, it says:

Note: In cases when the eventual publicPath 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.

My question: But how do I set this __webpack_public_path__ variable and where?

I thought I would have to set it in src/main.ts, but then I just get compiler error ERROR in ./src/main.ts

Cannot find name '__webpack_public_path__' when I build the project:

Isn't main.ts where I should set this variable? I even tried to set it in the built version of the file, main.js, and that didn't work either. Here is part of my Webpack config where I set the entry point.

config.entry = isTest ? {} : {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts' // our angular app
};
like image 503
Weblurk Avatar asked Dec 18 '22 17:12

Weblurk


1 Answers

compiler error ERROR in ./src/main.ts

TypeScript compiler errors are mostly just really powerful linting. More on this.

That compiler errors just tells you the TypeScript doesn't know about __webpack_public_path__. Just create globals.d.ts with :

declare var  __webpack_public_path__:string; 

And you should be golden. More on this 🌹

like image 136
basarat Avatar answered Dec 26 '22 11:12

basarat