lmarcelocc
lmarcelocc

Reputation: 1361

Webpack angular 4 file-loader

I'm using angular-starter.

Right now I'm trying to deploy to a test server. My problem is with the images located at src/assets/img.

My angular 4 code (component and view):

// Component
public ngOnInit() {
  this.logoUrl = require('../../assets/img/co-logo.png');
}

// View
<img flex src="{{logoUrl}}" alt="Logo">

Till here I don't have any issue.

My problem is understanding the behavior of webpack.

I've file-loader installed and I've added this piece of code (and tried a lot of others options) to webpack.common.js: Have tried with this options:

{
  test: /\.(png|jpe?g|gif)$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        outputPath: '/assets/img/',
        publicPath: '/',
        name: '[hash]_[name].[ext]',
      }
    }
  ],
}

The output seems not bad at all, I get this:

 » app  
  » dist  
   » assets  
    » img  
    - b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png

The issue

When loading the page, if I check the url of the image, it only retrieve me this:

/app/dist/01b401fa5bdbfdc4e3daf75d72fa76b9.png

I was expecting something like:

/app/dist/assets/img/b1249ef43aea4c57bcc7782f6a0ebb99_co-logo.png

I've tried, at least, with this parameters:

publicPath: '/assets/img/'
name: '/assets/img/[hash]_[name].[ext]'

Can anyone help me on this? I'm struggling with this since yesterday :/

Thank you all!

Edit: webpack code

Upvotes: 0

Views: 2684

Answers (1)

Rakesh Kumar Cherukuri
Rakesh Kumar Cherukuri

Reputation: 1271

Couple of things to make things clear and simple while resolving the issue

  1. Make sure webpack config has output.path pointed to the destination folder. I believe its app folder in your case. Do note that output.path takes absolute path i.e use path module.
  2. Take out publicPath in file-loader till we resolve the issue.
  3. Use relative path for file-loader's outputPath i.e. assets/img

Once you do those changes, things should work as expected. Then you can try putting back publicPath for file-loader depending on your need.

In general, i wouldn't use publicPath unless i have different environments to be taken care for ex. prod and dev. But thats just me.

Upvotes: 1

Related Questions