Solution of vue cli3 accessing static resources in public folder

  • 2021-08-10 06:35:19
  • OfStack

Today, static resources in the public folder were used in the project, and no problems were found in the local test, but the project deployed to the fat server reported 404 errors.

I found that the reason was that my project was not deployed at the root of the domain name, and I referenced the public file by absolute path, because there was a path error.

The path is as follows:

< img :src="`/image1.png`" >

Finding this situation in the official website document requires configuring publicPath prefix for URL: process.env.BASE_URL

The correct reference path is:

< img :src="`${process.env.BASE_URL}image1.png`" >

Of course, it is best to avoid putting files in the public folder, because any static resources placed in the public folder are simply copied without going through webpack.

Additional knowledge: @ vue/cli 3 Absolute path processing for package file reading

@ vue/cli 3 encapsulates webpack. config. js, which is generally configured in vue. config. js. Official website does not recommend output processing in webpack. I stepped on a pit here, hoping to help the friends I met later.

vue.config.js


module.exports = {
 //  Here is the configuration to read the current directory online, and the default is the root path, such as  /js, /css  And so on, according to the project 
 baseUrl: process.env.NODE_ENV === 'production' ? './' : '/',
 // others
}

Related articles: