Constantine Golub Constantine Golub - 13 days ago 7
Javascript Question

Generate images with Webpack and Angular2

I've got a small app in Angular2 that uses Webpack for building and scaffolding the project.

What I've faced is that I'm not able to load images for production that are specified in the TypeScript files. When I run the

npm run build
I don't find these images within the generated files (The images specified in the SCSS are generated).

Here is, below an example, how component looks like and my Webpack configuration looks very basic.

The main question is it possible to fix it, maybe need to add some Webpack loader for this case to handle it but I have not any idea being a newcomer to Webpack.

import { Component, OnInit, Injectable } from '@angular/core';

@Injectable()
@Component({
selector: 'custom-template',
templateUrl: './custom.html'
})

export class CustomComponent {
public data: any = [
{
image: '../../../assets/images/1.jpg',
text: 'Text 1...'
},
{
image: '../../../assets/images/2.jpg',
text: 'Text 2...'
},
{
image: '../../../assets/images/3.jpg',
text: 'Text 3...'
}
];
}

Answer

I believe the file-loader that Webpack provides is what you need. When you want to include a file, you can require it using the loader and it will return the relative path in the output.

Install it with:

npm install --save-dev file-loader

Your data would then look like this (provided the paths are relative to your file):

public data: any = [
    {
        image: require('file-loader!../../../assets/images/1.jpg'),
        text: 'Text 1...'
    },
    ...
];

This would produce something like this when evaluated:

public data: any = [
    {
        image: '/project-output-path/abcdef014ea5754463fac.jpg',
        text: 'Text 1...'
    },
    ...
];