4

This is related to this question.

We have a masthead component in Angular 1.6 that I am porting to Angular2 in a project using the Angular CLI. In Angular 1.6 it was simple to have an image alongside your controller and its CSS, and then easily reference it with a path relative to the component directory. For example:

-components
--my-component
---my-component.controller.js
---my-component.css
---my-image.jpg

In my-component.css:
 background-image: url(my-image.jpg);

According to the referenced question, this isn't possible with the Angular CLI. They recommend moving the image to an assets folder. Not an ideal solution, but okay. Surely if I split this component into its own node_module and import from there, Angular will be smart enough to allow paths relative to the node_module, right? So far, no luck there either.

So how are we expected to use node_modules that contain images specific to that module? The obvious work-around for us now is to add a postinstall script that copies the image from the module to the dependent project's assets folder - but that seems hacky and requires us to assume they have a particular asset folder setup.

In summary:

  • Is there some way to reference images that are located in a component folder relative to that folder?
  • If not, is there some way to reference images that are located in a node_module relative to the node_module?
  • If not, what's the best way to setup and maintain a module coupled with its images? Is postinstall the best idea for a work-around?

This one's racking my brain and it's the first time I've really questioned Angular2 and the CLI.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Jacob Ensor
  • 335
  • 3
  • 12

1 Answers1

0

The Angular CLI is going to cede control of image rendering to webpack, based on the settings that webpack includes by default. You can change the default settings by ejecting webpack from the Angular CLI by executing the ng-eject command. Once you have done this, you can reference your images in the webpack.config.js file.

Latin Warrior
  • 902
  • 11
  • 14