[Translation] webpack official website documentation: guide -- 22. public path

Original translation, please indicate the source when reprinting.

Original address: https://webpack.js.org/guides/public-path/

 

Webpack has a very useful configuration that specifies a base path for all assets in your application. It's called the public path.

 

example

There are several neat examples of this feature being used in practice.

 

set value at compile time

In development mode we usually have an assets/ folder at the same level as the index page. That's fine, but what if you wanted to put all your static resource files on the CND in production?

You can easily fix this by using a nice old environment variable. We have a variable called ASSET_PATH :

import webpack from'webpack';
 
// Whatever comes as an environment variable, otherwise use root
const ASSET_PATH = process.env.ASSET_PATH ||'/';
 
exportdefault{
  output:{
    publicPath: ASSET_PATH
  },
 
  plugins:[
    // This makes it possible for us to safely use env vars on our code
    newwebpack.DefinePlugin({
      'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH)
    })
  ]
};

 

Set value on the fly

Another use case is to set a public path in fly . You can use a global variable exported by webpack which is __webpack_public_path__ . So at the entry point of your application, it's as simple as:

__webpack_public_path__ = process.env.ASSET_PATH;

 

It can meet all your needs. Since we have used DefinePlugin in the configuration file , process.env.ASSET_PATH will always be defined, so we can use them safely.

 

warn

 

Note that __webpack_public_path__ will be assigned after the import is complete if imported using ES6 modules in the entry file. In this case, we would have to move the assignment of the public path to a specific module and then include it at the top of entry.js .

 

-- End --

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326692248&siteId=291194637