Angular 4为何在ng-build前替换背景URL?如何保留原CSS URL?
Hey, I get it—frustrating when the CLI messes with your CSS paths and breaks your background images. Let's break down why this is happening and how to fix it:
Angular CLI automatically adds hash suffixes to assets (like bg.ed946ca….jpg) during builds to handle cache busting, and it updates CSS references to match. But since your image ends up in dist/assets/bg.jpg instead of the hashed version, we need to tell the CLI to leave that URL alone.
Here are a few reliable solutions:
1. Adjust angular.json to Disable Hashing or Exclude Specific Assets
Open your project's angular.json file and tweak the build settings:
Option A: Disable All Asset Hashing (Simple but No Cache Busting)
If you don't mind losing cache busting for all assets, change the outputHashing value from all to none:
"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputHashing": "none", // ... rest of your config } }
This keeps all asset filenames (and their CSS references) exactly as they are.
Option B: Exclude Only Your Background Image from Hashing
If you want to keep cache busting for other assets but preserve bg.jpg, update your assets config and disable image optimization:
"assets": [ "src/favicon.ico", "src/assets", { "glob": "bg.jpg", "input": "src/assets/", "output": "assets/", "ignore": [] } ], "optimization": { "scripts": true, "styles": { "minify": true, "inlineCritical": true }, "fonts": true, "images": false // Turns off image hashing/optimization }
Now your bg.jpg will copy straight to dist/assets without a hash, and your CSS reference stays intact.
2. Use a Webpack Ignore Comment (Angular 14+)
If you're on Angular 14 or newer, add a special comment to your CSS rule to tell webpack (the tool under Angular CLI) not to modify the URL:
body { background: url(./assets/bg.jpg) /* webpackIgnore: true */; }
This is a quick, targeted fix that only affects this specific URL—no global config changes needed.
3. Switch to an Absolute Path
If your app is deployed at the root of your domain, use an absolute path in your CSS:
body { background: url(/assets/bg.jpg); }
This points directly to dist/assets/bg.jpg regardless of any CLI processing, and it works as long as your deployment root matches.
Just note that config options might vary a bit depending on your Angular version—double-check the docs for your specific release if something doesn't line up.
内容的提问来源于stack exchange,提问作者Дмитрий

