网页 综合 更新时间 2026-11-14 16:20:23

Public Path | webpack

自动蜘蛛 webpack.js.org 正文约 2523 字
Public Path | webpack
The publicPath configuration option can be quite useful in a variety of scenarios. It allows you to specify the base path for all the assets within your application.
There are a few use cases in real applications where this feature becomes especially neat. Essentially, every file emitted to your output.path directory will be referenced from the output.publicPath location. This includes child chunks (created via code splitting) and any other assets (e.g. images, fonts, etc.) that are a part of your dependency graph.
In development for example, we might have an assets/ folder that lives on the same level of our index page. This is fine, but what if we wanted to host all these static assets on a CDN in production?
To approach this problem you can easily use a good old environment variable. Let's say we have a variable ASSET_PATH:
Another possible use case is to set the publicPath on the fly. Webpack exposes a global variable called __webpack_public_path__ that allows you to do that. In your application's entry point, you can do this:
That's all you need. Since we're already using the DefinePlugin on our configuration, process.env.ASSET_PATH will always be defined so we can safely do that.
Be aware that if you use ES6 module imports in your entry file the __webpack_public_path__ assignment will be done after the imports. In such cases, you'll have to move the public path assignment to its own dedicated module and then import it on top of your entry.js:
There are chances that you don't know what the publicPath will be in advance, and webpack can handle it automatically for you by determining the public path from variables like import.meta.url, document.currentScript, script.src or self.location. What you need is to set output.publicPath to 'auto':
Note that in cases where document.currentScript is not supported, e.g., IE browser, you will have to include a polyfill like currentScript Polyfill.
Copyright OpenJS Foundation and webpack contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.
The OpenJS Foundation | Terms of Use | Privacy Policy | Bylaws | Code of Conduct | Trademark Policy | Trademark List | Cookie Policy
访问原文 返回搜索 https://webpack.js.org/guides/public-path/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。