Vue CLI构建时未生成backgrounds子目录,求vue.config配置指导
Hey there! I’ve run into this exact directory structure issue with Vue CLI before—let’s get your background subfolders showing up correctly in dist/img like you want.
The core problem is that Vue CLI’s default Webpack setup flattens asset subdirectories when building, which is why your desktop and mobile folders aren’t making it into the final dist folder. We can fix this by tweaking the asset handling rules in a vue.config.js file.
Step 1: Create/Edit vue.config.js
First, if you don’t already have one, create a vue.config.js file in your project’s root directory (right next to your src folder). This is where we’ll override the default Webpack config.
Step 2: Add the Configuration to Preserve Subdirectories
Paste this code into your vue.config.js:
module.exports = { chainWebpack: config => { // Modify the image handling rule to preserve background subdirectories config.module .rule('images') .use('url-loader') .tap(options => { return { ...options, // Customize the output path for background images name: (filePath) => { // Check if the file is in the backgrounds folder if (filePath.includes('backgrounds/')) { // Grab the path after "backgrounds/" (e.g., "desktop/bg.jpg") const relativePath = filePath.split('backgrounds/')[1]; // Output to dist/img/[relativePath] return `img/${relativePath}`; } // Keep default behavior for other images (flags, logos, etc.) return `img/[name].[hash:8].[ext]`; }, // Disable flattening to keep subdirectory structure flatten: false }; }); } };
How This Works
- The
chainWebpackmethod lets us modify Vue CLI’s existing Webpack config without overwriting everything. - We target the
imagesrule (which handles PNG/JPG/GIF/etc.) and adjust theurl-loaderoptions. - The
namefunction checks if an image is in yourbackgroundsfolder. If it is, it strips thebackgrounds/part of the path and outputs the file todist/img/[subfolder]/[filename]—sosrc/assets/backgrounds/desktop/bg.jpgbecomesdist/img/desktop/bg.jpg. flatten: falseensures Webpack doesn’t collapse subdirectories into the rootimgfolder.
Step 3: Rebuild Your Project
Run npm run build again, and you should see dist/img/desktop and dist/img/mobile populated with your background images!
Quick Check for CSS References
Just make sure you’re referencing your background images correctly in your CSS. For example:
body { background-image: url('~@/assets/backgrounds/desktop/main-bg.jpg'); }
The ~@/ tells Webpack to resolve the path from your src folder, which ensures the asset is picked up and processed correctly.
内容的提问来源于stack exchange,提问作者Michael Paccione

