When using Vue.js, handling static assets such as images can be somewhat nuanced due to the way Vue-CLI handles and serves files from different directories. The issue you're encountering is likely because Vue-CLI processes paths in CSS differently based on where the referenced file is located.
Understanding the Issue
- When you build your Vue app using Vue CLI, it processes your assets to optimize loading times and efficiency. This includes copying assets into the
dist directory, often under the assets folder, and updating paths in your CSS accordingly.
- Files placed in the
public directory, however, are copied directly to the dist directory without being processed. This is intended for assets that you don't want webpack to process (for example, files that are referenced directly by your index.html).
Solutions
Referencing the SVG Correctly
To correctly reference your logo.svg that's in the public folder, you should use an absolute path that starts with a / to ensure it's referencing the root of the served project. This means your CSS should look something like this:
background: url('/logo.svg');
Here, assuming logo.svg is directly inside your public directory, this path tells the browser to request logo.svg from the root of your deployed site, bypassing any webpack processing.
Moving the SVG to Assets
Another approach, if you want webpack to process the file (which could include optimizations like version hashing for caching purposes), is to move the logo.svg file to the src/assets directory. Then, reference it in your Vue component using a dynamic import. Assuming you're doing this inside a CSS file processed by webpack (for example, a .vue file's <style> block or a .css file imported into your JavaScript), you would do something like this:
/* Assuming logo.svg is now in the src/assets folder */
background: url('~@/assets/logo.svg');
Here, the tilde (~) and at sign (@) notation tells webpack to resolve the path as a module, with @ being an alias to the /src directory, which is standard in Vue CLI projects.
In Summary
- For assets that do not require webpack processing and that you want to reference as is, place them in the
public directory and reference them using absolute paths from the root (/).
- For assets that you want webpack to process (which includes copying them to the
dist directory with potential name hashing), place them in the src/assets directory and reference them using relative paths or the @ alias in your CSS.
This should resolve the issue you're facing with the incorrect path being used when your Vue app is built.