angular / angular-cli

CLI tool for Angular
https://cli.angular.io
MIT License
26.73k stars 11.98k forks source link

Module not found: Error: Can't resolve file #4778

Closed hassanasad closed 7 years ago

hassanasad commented 7 years ago
@angular/cli: 1.0.0-beta.32.3 [1.0.0-beta.28.3]
node: 7.5.0
os: darwin x64
@angular/common: 2.4.7
@angular/compiler: 2.4.7
@angular/core: 2.4.7
@angular/forms: 2.4.7
@angular/http: 2.4.7
@angular/platform-browser: 2.4.7
@angular/platform-browser-dynamic: 2.4.7
@angular/router: 3.4.7
@angular/cli: 1.0.0-beta.32.3
@angular/compiler-cli: 2.4.7

After the update to beta.32.3 i started getting these errors in SCSS files:

ERROR in ./src/app/shared/header/header.component.scss
Module not found: Error: Can't resolve './assets/images/icon-search.png' in '/Users/hassan/Code/app/shared/header'
 @ ./src/app/shared/header/header.component.scss 6:1898-1940
 @ ./src/app/shared/header/header.component.ts
 @ ./src/app/shared/shared.module.ts
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts

ERROR in ./src/app/shared/nav/nav.component.scss
Module not found: Error: Can't resolve './assets/fonts/portal.eot?' in '/Users/hassan/Code/src/app/shared/nav'
 @ ./src/app/shared/nav/nav.component.scss 6:295-332
 @ ./src/app/shared/nav/nav.component.ts
 @ ./src/app/shared/shared.module.ts
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts

The error seems to appear in this line:

background-image: url('assets/images/icon-search.png');

P.S: It was working fine on beta.31

billdwhite commented 7 years ago

Same thing here. Technically, at development time, the path is wrong because the file has not yet been compiled into the location it will be at runtime. So I'm assuming I need to specify the location in the configuration somewhere?

hassanasad commented 7 years ago

For reference my .angular-cli.json file has:

"assets": [
        "assets",
        "web.config"
      ],

(Which was working fine in beta.31 as mentioned earlier)

billdwhite commented 7 years ago

I've got the same; still getting the error

armangevorgyan commented 7 years ago

me too @font-face { font-family: 'Segoe UI'; src: url('../assets/fonts/SegoeUI.eot'); src: url('../assets/fonts/SegoeUI.eot?#iefix') format('embedded-opentype'), url('../assets/fonts/SegoeUI.woff') format('woff'), url('../assets/fonts/SegoeUI.ttf') format('truetype'); font-weight: normal; font-style: normal; }

ERROR in ./src/app/components/footer/footer.scss Module not found: Error: Can't resolve '../assets/fonts/SegoeUI.eot' in '/home/arman/Projects/AOP/src/app/components/footer' @ ./src/app/components/footer/footer.scss 6:83-121 6:144-182 @ ./src/app/components/footer/footer.ts @ ./src/app/index.ts @ ./src/main.ts @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts

clydin commented 7 years ago

CSS URL handling was changed. To replicate the behavior prior to beta.32, use a root relative URL (i.e., add a / to the beginning of each URL).

billdwhite commented 7 years ago

I tried that and it did compile with no errors, but then at runtime it was looking for 'assets' in the root of the url rather than in the root of the web context. So none of my images loaded.....

hassanasad commented 7 years ago

Thanks @clydin - it started working again for me by adding '/' before all relative URLs in the SCSS files.

@billdwhite do you have the 'assets' in your .angular-cli.json file as mentioned above?

billdwhite commented 7 years ago

Yes I do have that in my files. But I'm running the app from a subcontext (think http://myserver/myapp as opposed to http://myserver) so the path that results from using / before the relative urls results in it looking for http://myserver/assets/myimage.png which is wrong. (It needs to be http://myserver/my app/assets/myimage.png) so I'm guessing I'm missing some other config setting that tells it to adjust for that. Maybe base href or something but that seems to be set correctly for everything else in my app so I'm not sure what I'm missing. Again, setting the / does fix the compile errors but it just doesn't work at runtime.

kunee commented 7 years ago

I have the exact same behaviour as @billdwhite. Adding a slash maybe fixes the compilation error but it's no final solution and wasn't necessary in the past.

billdwhite commented 7 years ago

@filipesilva is it possible this was caused by your commit from 3 days back?

filipesilva commented 7 years ago

Yes it is likely related. I'll have a look.

clydin commented 7 years ago

url()'s in component stylesheets are now processed. This allows the CLI to hash the assets and supports long-term caching. However, the URL now needs to be build-time discoverable and the path must be relative to the component stylesheet for this to work. This also has the advantage that component based assets can be encapsulated within the component source location, if desired.

If you don't want them processed, a root relative URL will prevent this behavior. Unfortunately, this will currently conflict with custom base hrefs and deployUrls. This is in the process of being corrected.

Also of note is that global stylesheets already function in this manner.

filipesilva commented 7 years ago

First of all, apologies for the breakage. @clydin's answer above explains what happened well. Further clarification: 'root relative URLs' are those that start with /.

As to why this change... it was because component css did not support imports, and in fixing that we inadvertently also fixed url() inside css.

Before it didn't actually work insofar as images/etc where never processed. Now they are (as long as it's a relative url).

This also means that you can just put your images locally, side by side with your css. They will be correctly recognized and placed in the output directory, and even get hashes on prod builds. You don't need to put them in assets/ if you don't want to.

If you do want to put them in assets/, you can use a root relative path, one starting with /.

For instance, from src/app/component.css you can use the relative path url('../assets/image.jpg') or the absolute path url('/assets/image.jpg'.

I just pushed a PR that should fix base-href and deploy-url broken interaction: https://github.com/angular/angular-cli/pull/4803.

arntj commented 7 years ago

@filipesilva Thanks for your clarification. However, I'm still having problem with images not being copied in production builds, see #4806. I don't know if this was fixed in your fix?

romulo1984 commented 7 years ago

If url() is now processed, I believe @import should follow the same way.

In my less file I'm having to use two ways to reference a file.

@import "../../../assets/less/bootstrap/_variables.less"; background-image: url ('/assets/img/professional-02.jpg');

assets in the two cases above is the same folder, but I can not use /assets in @import.

filipesilva commented 7 years ago

@romulo1984 imports and urls follow different semantics.

skdhayal commented 7 years ago

Thanks @clydin... :)

Save my time :)

doronnac commented 7 years ago

according to base tag specification

The base URL to be used throughout the document for relative URL addresses. If this attribute is specified, this element must come before any other elements with attributes whose values are URLs. Absolute and relative URLs are allowed.

in angular-cli projects the base href is "/" (index.html) so all paths, including urls in css, and including relative and absolute paths, should have / appended to them. Instead, relative paths have './'

The solution of manually adding '/' for absolute paths is not good enough, since different server environments on different builds might differ in the wanted 'base' url.

I assume it's a loader issue. Not sure how it plays with the rest of the configuration, but raw-loader follows this spec perfectly.

moorthi07 commented 7 years ago

"@angular/cli" :"1.0.0-rc.4", - throws 404 error for urls in '.html' files

GET http://localhost:4200/resources/files.json 404 (Not Found) scheduleTask @ zone.js:2019 ZoneDelegate.scheduleTask @ zone.js:353 onScheduleTask @ zone.js:241 ZoneDelegate.scheduleTask @ zone.js:347 Zone.scheduleTask @ zone.js:196 Zone.scheduleMacroTask @ zone.js:210 (anonymous) @ zone.js:2043 send @ VM8905:3 (anonymous) @ xhr_backend.js:126 Observable._trySubscribe @ Observable.js:57 Observable.subscribe @ Observable.js:45 (anonymous) @ toPromise.js:68 ZoneAwarePromise @ zone.js:729 toPromise @ toPromise.js:66 webpackJsonp.647.NodeService.getFiles @ app.treeservice.ts:13 webpackJsonp.432.AppComponent.ngOnInit @ app.component.ts:61 Wrapper_AppComponent.ngDoCheck @ /AppModule/AppComponent/wrapper.ngfactory.js:22 View_AppComponent_Host0.detectChangesInternal @ /AppModule/AppComponent/host.ngfactory.js:36 AppView.detectChanges @ view.js:425 DebugAppView.detectChanges @ view.js:620 ViewRef_.detectChanges @ view_ref.js:170 (anonymous) @ application_ref.js:625 ApplicationRef_.tick @ application_ref.js:625 ApplicationRef_._loadComponent @ application_ref.js:600 ApplicationRef_.bootstrap @ application_ref.js:588 (anonymous) @ application_ref.js:400 PlatformRef_._moduleDoBootstrap @ application_ref.js:400 (anonymous) @ application_ref.js:352 ZoneDelegate.invoke @ zone.js:334 onInvoke @ ng_zone.js:273 ZoneDelegate.invoke @ zone.js:333 Zone.run @ zone.js:126 (anonymous) @ zone.js:713 ZoneDelegate.invokeTask @ zone.js:367 onInvokeTask @ ng_zone.js:264 ZoneDelegate.invokeTask @ zone.js:366 Zone.runTask @ zone.js:166 drainMicroTaskQueue @ zone.js:546 error_handler.js:54 EXCEPTION: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:4200/resources/files.json ErrorHandler.handleError @ error_handler.js:54 next @ application_ref.js:348 schedulerFn @ async.js:93 SafeSubscriber.__tryOrUnsub @ Subscriber.js:234 SafeSubscriber.next @ Subscriber.js:183 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ async.js:79 NgZone.triggerError @ ng_zone.js:333 onHandleError @ ng_zone.js:294 ZoneDelegate.handleError @ zone.js:338 Zone.runGuarded @ zone.js:142 _loop_1 @ zone.js:557 drainMicroTaskQueue @ zone.js:566 ZoneTask.invoke @ zone.js:424 error_handler.js:59 ORIGINAL STACKTRACE: ErrorHandler.handleError @ error_handler.js:59 next @ application_ref.js:348 schedulerFn @ async.js:93 SafeSubscriber.__tryOrUnsub @ Subscriber.js:234 SafeSubscriber.next @ Subscriber.js:183 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ async.js:79 NgZone.triggerError @ ng_zone.js:333 onHandleError @ ng_zone.js:294 ZoneDelegate.handleError @ zone.js:338 Zone.runGuarded @ zone.js:142 _loop_1 @ zone.js:557 drainMicroTaskQueue @ zone.js:566 ZoneTask.invoke @ zone.js:424 error_handler.js:60 Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:4200/resources/files.json at resolvePromise (zone.js:665) [angular] at resolvePromise (zone.js:636) [angular] at :4200/vendor.bundle.js:109704:17 [angular] at Object.onInvokeTask (ng_zone.js:264) [angular] at ZoneDelegate.invokeTask (zone.js:366) [angular] at Zone.runTask (zone.js:166) [<root> => angular] at drainMicroTaskQueue (zone.js:546) [<root>] at XMLHttpRequest.ZoneTask.invoke (zone.js:424) [<root>] ErrorHandler.handleError @ error_handler.js:60 next @ application_ref.js:348 schedulerFn @ async.js:93 SafeSubscriber.__tryOrUnsub @ Subscriber.js:234 SafeSubscriber.next @ Subscriber.js:183 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ async.js:79 NgZone.triggerError @ ng_zone.js:333 onHandleError @ ng_zone.js:294 ZoneDelegate.handleError @ zone.js:338 Zone.runGuarded @ zone.js:142 _loop_1 @ zone.js:557 drainMicroTaskQueue @ zone.js:566 ZoneTask.invoke @ zone.js:424 zone.js:522 Unhandled Promise rejection: Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…e>Cannot GET /resources/files.json</pre>↵</body>↵", status: 404, ok: false, statusText: "Not Found", headers: Headers…} ; Zone: angular ; Task: Promise.then ; Value: Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…e>Cannot GET /resources/files.json</pre>↵</body>↵", status: 404, ok: false, statusText: "Not Found", headers: Headers…} undefined consoleError @ zone.js:522 handleUnhandledRejection @ zone.js:527 _loop_1 @ zone.js:562 drainMicroTaskQueue @ zone.js:566 ZoneTask.invoke @ zone.js:424 zone.js:524 ZoneAwareError {__zone_symbol__error: Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:4200/res…, rejection: Response, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask…} consoleError @ zone.js:524 handleUnhandledRejection @ zone.js:527 _loop_1 @ zone.js:562 drainMicroTaskQueue @ zone.js:566 ZoneTask.invoke @ zone.js:424 Mal.png:1 GET http://localhost:4200/assets/Mal.png 404 (Not Found) Molly.png:1 GET http://localhost:4200/assets/Molly.png 404 (Not Found) Sophie.png:1 GET http://localhost:4200/assets/Sophie.png 404 (Not Found) Taz.png:1 GET http://localhost:4200/assets/Taz.png 404 (Not Found) Porter.png:1 GET http://localhost:4200/assets/Porter.png 404 (Not Found) Stephen.png:1 GET http://localhost:4200/assets/Stephen.png 404 (Not Found) Kobe.png:1 GET http://localhost:4200/assets/Kobe.png 404 (Not Found) Cinny.png:1 GET http://localhost:4200/assets/Cinny.png 404 (Not Found) Hermes.png:1 GET http://localhost:4200/assets/Hermes.png 404 (Not Found)

moorthi07 commented 7 years ago

I fixed it by moving 'resources' folder inside 'assets' - folder as its manageable workaround for me. But , I actually need to access a folder from the root. In angular-cli.json if I set 'resources' folder inside 'assets' : array, its still not working!

"assets": [ "assets", //-------- Folder "resources" //-------Folder ], Whats wrong here, that angular-cli to throw the above errror?

sqrter commented 7 years ago

Hi, I use cli version 1.0.0. I'm deploying to non-root path within a domain and my build script executes the following command:

ng build \
--target=production --output-path=dist/de \
--deploy-url=/site/v2/de/ \
--base-href=/site/v2/de/ \
--i18n-file=src/i18n/messages.de.xlf --locale=de

One of my components has the scss style:

background-image: url('/assets/images/logo-de.svg');

After the build the style is transformed to:

background-image:url(/site/v2/de/site/v2/de/assets/images/logo-de.svg

It seems like it concatenates deploy-url and base-href which is a wrong behavior I guess. However everything is working while serving it in development mode with ng serve.

PS. If I place the images within the component folder and use relative url like this background-image: url('./images/logo-de.svg') everything works perfect.

Update. Looks like the logic is here https://github.com/angular/angular-cli/blob/master/packages/%40angular/cli/models/webpack-configs/styles.ts#L66 but still can't understand why it's not possible to have both deploy-url and base-href without scheme.

jonathanargentiero commented 7 years ago

It was an empty background-image: url('') in my case.

gaojinbo010 commented 7 years ago

when is set url like this , it has error: background-image: url('assets/img/1.jpg');

if you used angular2-webpack-starter you can try like this, it works for me ! background-image: url('~assets/img/1.jpg');

spark-studio commented 7 years ago

Hi, one solution for me is, put some styles like this in:

styles.css / You can add global styles to this file, and also import other style files /

nputhiyadath commented 7 years ago

I am facing a similar problem with @angular/cli version 1.0.0. I am using the path in sass as background-image: url('/assets/images/account.png') And this works fine with ng serve and I can see images. ng build also does not give any error. But after I build it, the main bundle has wrong path. It has

background-image: url('/./assets/images/account.png')

Note that I am using "ng build --env prod --base-href ." to build the project.

Does anyone know which version has the fix for this?

bobrosoft commented 7 years ago

Solved that by disabling of url(...) processing in css-loader plugin (I using external webpack config from angular2-webpack-starter). Described here https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/246#issuecomment-308438193

aliyeysides commented 6 years ago

@billdwhite hey did you ever end up solving your issue? I'm facing the same scenario.

billdwhite commented 6 years ago

@aliyeysides that was so many months back that I'm not sure how I solved it. Regardless, I have been using ~ in my asset paths to like this:

@import '~assets/styles/variables.scss';

so maybe that will work for you to specify an assets folder in the root of the project that is running from a non-server root endpoint.

sunarc-rahul commented 6 years ago

[](ERROR in multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js Module not found: Error: Can't resolve 'script-loader' in 'C:\rahul\angular\test\abc' @ multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js

ERROR in multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js Module not found: Error: Can't resolve 'script-loader' in 'C:\rahul\angular\test\abc' @ multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js

ERROR in multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js Module not found: Error: Can't resolve 'script-loader' in 'C:\rahul\angular\test\abc' @ multi script-loader!./~/jquery/dist/jquery.slim.js script-loader!./~/popper.js/dist/umd/popper.min.js script-loader!./~/bootstrap/dist/js/bootstrap.min.js

ERROR in multi ./~/bootstrap/dist/css/bootstrap.min.css ./src/styles.css Module not found: Error: Can't resolve 'postcss-loader' in 'C:\rahul\angular\test\abc' @ multi ./~/bootstrap/dist/css/bootstrap.min.css ./src/styles.css

ERROR in multi ./~/bootstrap/dist/css/bootstrap.min.css ./src/styles.css Module not found: Error: Can't resolve 'postcss-loader' in 'C:\rahul\angular\test\abc' @ multi ./~/bootstrap/dist/css/bootstrap.min.css ./src/styles.css

ERROR in multi ./src/polyfills.ts Module not found: Error: Can't resolve '@ngtools/webpack' in 'C:\rahul\angular\test\abc' @ multi ./src/polyfills.ts

ERROR in multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts Module not found: Error: Can't resolve '@ngtools/webpack' in 'C:\rahul\angular\test\abc' @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

ERROR in Error: Child compilation failed: Entry module not found: Error: Can't resolve 'raw-loader' in 'C:\rahul\angular \test\abc': Error: Can't resolve 'raw-loader' in 'C:\rahul\angular\test\abc'

ERROR in multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts Module not found: Error: Can't resolve 'webpack-dev-server/client?http://localhost:4200' in 'C:\rahul\angular\test\abc' @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts ) Please help me on this

ululajib commented 6 years ago

Please help me ...

npm run dev @ dev /var/www/html/screp npm run development @ development /var/www/html/screp cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js 95% emitting

ERROR Failed to compile with 1 errors 00:33:59

This dependency was not found:

/var/www/html/screp/resources/assets/sass/app.scss in multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss To install it, you can run: npm install --save /var/www/html/screp/resources/assets/sass/app.scss Asset Size Chunks Chunk Names /js/app.js 4.12 kB 0 [emitted] /js/app

ERROR in ./resources/assets/js/app.js Module build failed: ReferenceError: Unknown plugin "transform-object-rest-spread" specified in "base"t > 0, attempted to resolve relative to "/var/www/html/screp/resources/assets/js" at /var/www/html/screp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17

at Array.map () at Function.normalisePlugins (/var/www/html/screp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20) at OptionManager.mergeOptions (/var/www/html/screp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36) at OptionManager.init (/var/www/html/screp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12) at File.initOptions (/var/www/html/screp/node_modules/babel-core/lib/transformation/file/index.js:212:65) at new File (/var/www/html/screp/node_modules/babel-core/lib/transformation/file/index.js:135:24) at Pipeline.transform (/var/www/html/screp/node_modules/babel-core/lib/transformation/pipeline.js:46:16) at transpile (/var/www/html/screp/node_modules/babel-loader/lib/index.js:50:20) at /var/www/html/screp/node_modules/babel-loader/lib/fs-cache.js:118:18 at ReadFileContext.callback (/var/www/html/screp/node_modules/babel-loader/lib/fs-cache.js:31:21) at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:437:13) @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss ERROR in multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss> Module not found: Error: Can't resolve 'css-loader' in '/var/www/html/screp' @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

xtgrant commented 6 years ago

@filipesilva @romulo1984 Hi. In reference to @romulo1984 comment about

@import "../../../assets/less/bootstrap/_variables.less";
background-image: url ('/assets/img/professional-02.jpg');

assets in the two cases above is the same folder, but I can not use /assets in @import.

How would you add a root reference in @import?

For example: Convert: @import "../../../assets/less/bootstrap/_variables.less"; To point to a common folder: @import "common/less/bootstrap/_variables.less";

Because in my current implementation this currently creates an error in saying it cannot resolve the path location. Error:

Module build failed:
@import "common/variables";
      File to import not found or unreadable: common/variables.

I have defined the "common" path mapping in tsconfig.json:

"paths": {
        "common/*": [
            "app/common/styles*"
        ]
    }

and yes, "variables.scss" does exist in the "app/common/styles" folder. Also, using the "~" infront of it does not work either.

mseltene commented 6 years ago

background-image: url('/assets/images/icon-search.png'); works on mine, add / to assests... so /assets... and also don't do background-image: url(""); empty source with double"" or single'' quotes, it gave me error saying ERROR in ./src/styles.css Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve './.' in ......

dcatoday commented 6 years ago

Is this broken again in 1.7.0?

rodrijuarez commented 6 years ago

@dcatoday having the same problem as you in 1.7.0, I think it's broken again

tkohr commented 6 years ago

I still don't see a clean way, how to reference urls in sass with a relative path that works both in dev and prod (app not running in root directory).

If I reference my image and font urls with 'root relative urls' like url('/assets/some-font.ttf') everything works fine in dev but I can not run my app in a subfolder on the server.

If I use relative urls starting from my sass file like url('../fonts/some-font.ttf'), my dev environment works fine as well but all assets referenced in sass get packaged into the root of my app instead of the assets folder.

For reasons of our deployment process and prod environment I am not using base href, but HashLocationStrategy.

woteska commented 6 years ago

Guys, Google Mobile Friendly Test failed (https://search.google.com/test/mobile-friendly), because it was not able to find the background-image. This is how I started to search for a solution. Actually starting with '/' didn't help me at all... but starting with './' was the solution. (Angular 6)

image

FrancescoBorzi commented 5 years ago

I'm running Angular CLI version 6.2.4 and I still have the same issue reported before by @billdwhite:

Yes I do have that in my files. But I'm running the app from a subcontext (think http://myserver/myapp as opposed to http://myserver) so the path that results from using / before the relative urls results in it looking for http://myserver/assets/myimage.png which is wrong. (It needs to be http://myserver/my app/assets/myimage.png) so I'm guessing I'm missing some other config setting that tells it to adjust for that. Maybe base href or something but that seems to be set correctly for everything else in my app so I'm not sure what I'm missing. Again, setting the / does fix the compile errors but it just doesn't work at runtime.

this happens only in production and only when the app runs in a subdomain.

matulkum commented 5 years ago

Just want to add another vote.. because paths in my scss is also not working for me. If I do not absolute it works when running with ng serve but not in prduction and the other way around when I go relative. This the line in one of my components scss files: background-image: url("assets/bar.png");

EDIT: actually I just found I had another bug in my scss, which was the real cause for it not working in production. I had:

background: cover #da4877;
background-image: url("/assets/bar.png");
background-size: cover;

after I changed the first line to background: #da4877; it works.

So please Ignore my vote on this ;)

isahilpahuja commented 5 years ago

I'm running Angular CLI version 6.2.4 and I still have the same issue reported before by @billdwhite:

Yes I do have that in my files. But I'm running the app from a subcontext (think http://myserver/myapp as opposed to http://myserver) so the path that results from using / before the relative urls results in it looking for http://myserver/assets/myimage.png which is wrong. (It needs to be http://myserver/my app/assets/myimage.png) so I'm guessing I'm missing some other config setting that tells it to adjust for that. Maybe base href or something but that seems to be set correctly for everything else in my app so I'm not sure what I'm missing. Again, setting the / does fix the compile errors but it just doesn't work at runtime.

this happens only in production and only when the app runs in a subdomain.

Hey, did you find any solution for this issue? I'm facing the same issue.

Empereol commented 5 years ago

@isahilpahuja , the workaround (not a proper solution) I've found is to move your image reference from the styles to the template. It feels icky but it "works."

So instead of:

// article.scss
.article__photo {
  background-image: url(assets/bacteria.svg);
}

do this instead:

<!-- article.html -->
<div class="article__photo" style="background-image: url(assets/bacteria.svg);"></div>

Though this workaround may not be reasonable if you're wanting to apply the background image to many elements.

Another possible workaround is to eject the webpack config and fiddle with the CSS file-loading, though I'm no webpack expert but I assume it could likely be done... Of course, at the expense of the ejected webpack config which I personally find intimidating...

isahilpahuja commented 5 years ago

@Empereol Thanks a lot! I moved it from styles to template and it worked. But still didn't able to find the reason why it was not working when placed in scss file.

thorhunter1 commented 5 years ago

Any update on this? This problem has been there very long now and it's still not being addressed. I was not able to find clean way to reference assets in scss files that would work both for dev and production. Absolute path works in dev environment but not in prod when application is hosted in subdomain, relative path on the other hand forces me to reference different path depending on location of scss file.

hieutranagi47 commented 5 years ago

The problem still is here - Jun 2019 But I found lukaszmn's solution can solve the issue with background: url("~src/assets/foo.svg") instead of url(/assets/foo.svg).

fergardi commented 5 years ago

This was working for me just fine in Angular7 with the url('/assets/foo.png'). As soon as I migrated to Angular 8 It broke again, and I must use url('~src/assets/foo.png').

Any news?

julianpoemp commented 5 years ago

Until now I have faced the same problem. url("/assets/...") worked well with ng serve but not on my production server with an different base-href than "/". It redirected to <domain>/assets/.. instead of <domain>/<subfolder>/assets (<domain>/<subfolder>/ is my base-href).

Now I can confirm the following using Angular 8:

I'm now using just "assets/..." and it works for me on development and production.

EDIT: I don't know why, but my images are copied next to the assets folder but there are copies in my assets folder, too. Does anyone knows the reason?

royling commented 5 years ago

I'm now using just "assets/..." and it works for me on development and production.

EDIT: I don't know why, but my images are copied next to the assets folder but there are copies in my assets folder, too. Does anyone knows the reason?

@julianpoemp this is well explained above https://github.com/angular/angular-cli/issues/4778#issuecomment-280798718, url() in component styles is processed.

Paitum commented 5 years ago

Problem

I am having a similar problem; ng serve works fine, but the CSS produced by ng build --base-href="./" transforms url()'s from url(/fonts/roboto/roboto-latin.woff2) to url(/./fonts/roboto/roboto-latin.woff2) (notice the root-relative slash). The desired output would be url(./fonts/roboto/roboto-latin.woff2) (a relative url) which should result in the browser loading it relative to the HTML's <base href="./">.

I have manually replaced the url(/./ with url(./ and seen the CSS load properly based on the <base href>, and am struggling to figure out how to configure the Angular CLI (6.2.9) to produce relative url()s.

More details:

We build artifacts without knowing where they will be deployed. Deploying artifacts involves setting the <base href> appropriately, so all resources are relative to the correct base.

I have read the responses by @clydin https://github.com/angular/angular-cli/issues/4778#issuecomment-280773798, and @filipesilva https://github.com/angular/angular-cli/issues/4778#issuecomment-280798718, but find them confusing because:

I have read (https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/246#issuecomment-308438193) that disabling the url processing by the css-loader is a solution, but haven't tried it out yet. After 2 years of this problem, I would be surprised if the Angular CLI didn't have first-class support for this.

Does the Angular CLI have a solution to this problem, or is a custom Webpack Config the "correct" solution? If yes, then what version of the Angular CLI supports the solution (since we are using v6)?

angular-automatic-lock-bot[bot] commented 4 years ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.