when webpack packages a project, you often have to deal with the path problem of resources, and there are usually several solutions
.- do not set
publicPath
, and generate page-based relative paths - set
publicPath
, relative path and absolute path can be set - set ides/public-path/" rel=" nofollow noreferrer ">
_ _ webpack_public_path__
, the resource path in js uses this variable, but the resource in css does not use
Project path:
the development environment is based on the /
root directory, so no matter how to set the OK, to the test environment and production environment path will not be able to adapt.
Development Environment Page address:< hr >http://localhost:8080/index.html
Development Environment Resource path:http://localhost:8080/[js|css|img]
Test Environment Page address:< hr >http://www.test.com/webapp/aaa/index.html
Test Environment Resource path:http://cdn.test.com/static/aaa/[js|css|img]
production environment page address:< hr >http://www.prod.com/webapp/aaa/index.html
production environment resource path:http://cdn.prod.com/static/aaa/[js|css|img]
question: the test environment and production environment will only be packaged once. How can the img paths in js and css adapt to different environments?
there are several key points to solve this problem first
1, the domain name and path of page and resource are different, you cannot simply use the relative path
2, the relative path in js is for the current page, the relative path in css is for the current css file
3, js can define resource path prefix variables, css cannot use
4, and you can setpublicPath
separately for resource types.
problem solving ideas
1. The resource path in js is used to introduce external variables.
for example,: var imgPath = window.staticPath; / / window.staticPath is injected into index.html from the background
from
to
to dynamic src is that webpack cannot package the images under assets under the dist/img path if the dynamic stitching address is not recognized. Of course, a small trick is to set both src.
2, _ _ webpack_public_path__
variable
variable
for example: _ webpack_public_path__ = window.resourcePath;
/ / window.resourcePath injects
js into index.html
the drawback of this approach is that img url in css cannot be used
3, publicpath
,
{
name: "img/[name].[ext]",
publicPath:"../",
limit: 1024
}
because publicPath
has a higher priority than _ _ webpack_public_path__
, the disadvantage is that img src in js also uses this publicpath, while the relative path in js is based on the current page
4. After looking through the file-loader source code, we find that publicpath, can actually be defined as a function,
, so there is a silly way to set publicpath dynamically
{
name: "img/[name].[ext]",
publicPath: function(url){
if(assetsUtil.useWebpackPath(url)){
return `__webpack_public_path__ + ${JSON.stringify(url)}`
}
return "../"
},
limit: 1024
}
the disadvantage is which resources need to maintain absolute paths and which use relative paths