UNPKG

webpack-dynamic-public-path

Version:
87 lines (69 loc) 2.19 kB
# Dynamic Public Path Plugin Replace publicPath inside a chunk, or chunks, to a variable. [![NPM](https://nodei.co/npm/webpack-dynamic-public-path.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/webpack-dynamic-public-path/) ## Usage > :warning: This plugin is compatible only with webpack 4. If you use webpack 5 - check official guide https://webpack.js.org/guides/public-path/#automatic-publicpath **webpack.config.js** ```js const WebpackDynamicPublicPathPlugin = require("webpack-dynamic-public-path"); module.exports = { output: { publicPath: "publicPathPlaceholder", }, plugins: [ new WebpackDynamicPublicPathPlugin({ externalPublicPath: "window.externalPublicPath" }), ] } ``` **bundle.js** ```js // before __webpack_require__.p = "publicPathPlaceholder"; // after __webpack_require__.p = window.externalPublicPath; ``` ## Options ```ts interface Options { externalPublicPath: string; // JavaScript code, here you can define some variable or condition. chunkNames: string[]; // Chunk names in which `publicPath` will be replaced. } new WebpackDynamicPublicPathPlugin(options: Options); ``` ### `chunkNames` In case if you have several entries you should define plugin instance for each of them. Check example. **webpack.config.js** ```js const WebpackDynamicPublicPathPlugin = require("webpack-dynamic-public-path"); module.exports = { entry: { 'index': path.resolve(__dirname, 'src', 'index.js'), 'second-chunk': path.resolve(__dirname, 'src', 'second-chunk.js') }, output: { filename: '[name].bundle.js', publicPath: "publicPathPlaceholder" }, plugins: [ new WebpackDynamicPublicPathPlugin({ externalPublicPath: "window.externalPublicPathForMainChunk", chunkNames: ['index'] }), new WebpackDynamicPublicPathPlugin({ externalPublicPath: '"./"', chunkNames: ['second-chunk'] }), ] } ``` **index.bundle.js** ```js __webpack_require__.p = window.externalPublicPathForMainChunk; ``` **second-chunk.bundle.js** ```js __webpack_require__.p = "./"; ```