Images GETs throw 404 error in production using Webpack and AngularJS

image not loading in angular 7
angular get all images from folder
angular image not showing
image not loading in angular 8
angular assets not found
how to upload image in assets folder in angular 6
angular.json assets
angular assets path

I have this conundrum I can't solve after many tryouts:

I'm unable to load static images in production;

everything is fine while developing (npm run serve), even when serving files from dist (npm run serve:dist)

Versions

Webpack: 3.12.0

file-loader: 1.1.11

url-loader: 1.1.2

AngularJS: 1.6.9

While developing:

My index.html contains this line and webpack won't load without

<base href="/"></base>

while my AngularJS config block contains

$locationProvider.hashPrefix('');

I use an URL like http://localhost:3000/#/appName/listingComponent/users

and I'm able to see every image using the ng-src (sometimes it's dynamically binded) like this

<img ng-src="app/images/image1.png">

the folder structure is like this

ui/
├── conf/
│   ├── browsersync-dist.conf.js
│   ├── browsersync.conf.js
│   ├── gulp.conf.js
│   ├── webpack-dist.conf.js
│   └── webpack.conf.js
├── gulp_tasks/
│   ├── browsersync.js
│   ├── misc.js
│   └── webpack.js
├── node_modules/
├── src/
│   ├── app/
│   │   ├── config.js  //global variables
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   ├── index.js
│   │   ├── index.less
│   │   ├── images/ <--
│   │   ├── actual_app_folders/
│   │   └── ...
├── gulpfile.js
└── package.json

In my webpack-dist.js I have the following

module.exports = {
  module: {
    loaders: [
      {
        test: /\.json$/,
        loaders: [
          'json-loader'
        ]
      },
      {
        test: /\.js$/,
        exclude: [
          /node_modules/
        ],
        loader: 'babel-loader',
        options: {
          presets: ['es2015']
        }
      },
      {
        test: /\.js$/,
        exclude: [
          /node_modules/
        ],
        loaders: [
          'eslint-loader'
        ],
        enforce: 'pre'
      },
      {
        test: /\.(css|less)$/,
        exclude: '/node_modules/roboto-fontface/',
        loaders: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?minimize!less-loader!postcss-loader'
        })
      },
      {
        test: /\.html$/,
        loaders: [
          'html-loader'
        ]
      },
      {
        test: /\.(jpe?g|png|gif|svg|eot|woff|ttf|svg|woff2)$/,
        loader: 'url-loader?name=[name].[ext]'
      }
    ]
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    FailPlugin,
    new HtmlWebpackPlugin({
      template: conf.path.src('/app/index.html'),
      inject: true,
      chunksSortMode: 'dependency'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: ['vendors', 'config'],
      minChunks: Infinity
    }),
    new ExtractTextPlugin('index-[contenthash].css'),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: () => [autoprefixer]
      }
    })
  ],
  output: {
    path: conf.paths.dist,
    filename: function(output) {
      return output['chunk']['name'] === 'config' ? '[name].js' : '[name]-[hash].js';
    },
    chunkFilename: '[name]-[hash].js'
  },
  entry: {
    app: `./${conf.path.src('/app/index')}`,
    config: `./${conf.path.src('/app/config')}`,
    vendors: Object.keys(pkg.dependencies).concat(['webpack-material-design-icons'])
  }
};
IN PRODUCTION

The build process adds the /customer_company_name/our_company_name/ prefix to the path, which becomes

http://<customer_domain>:<domain_port>/customer_company_name/our_company_name/#/appName/listingComponent/users

while the folder structure is like this

our_company_name/
├── app/
│   ├── images/ <--
│   │   ├── image1.png
│   │   └── image2.png
├── app-<random_number>.js
├── config.js
├── favicon.ico
├── index.html
├── index-<random_number>.css
└── vendors.js

THE PROBLEM

Now every time there's a pic to be shown, the browser gets a 404 error like this

GET http://<customer_domain>:<domain_port>/app/images/image1.png 404 (Not Found)

while the request should be made like this

GET http://<customer_domain>:<domain_port>/customer_company_name/our_company_name/index.js

like every other file in the application does.

What I tried

So far nothing of the following helped:

  1. Change base tag upon build process in the following <base href="/customer_company_name/our_company_name/"></base> (this is currently retained)
  2. Explicitly requiring the pictures together with every other file in the index.js require('./images/ODM_trasp48px.png'); (this is currently retained)
  3. Using publicPath in webpack output.publicPath: '/customer_company_name/our_company_name/' and also output.publicPath: '/'
  4. Using file-loader instead of url-loader (this is currently retained)
  5. Using file-loader with options: { useRelativePath: true }
  6. Using file-loader with options: { publicPath: /customer_company_name/our_company_name/ }

Can you help me lads, please?

I think the problem is not with the replacement pattern since it works for other file types, but the fact that webpack does not know what to do with ng-src attribute. I think it only looks at the img's src attribute by default. You can change it to recognize ng-src like:

module.exports = {
  module: {
    loaders: [
    ...
    {
      test: /\.html$/,
      loaders: [ "html-loader?" + JSON.stringify({ attrs: ["img:src", "img:ng-src"] })]
    },
    ...
  ],
   ...

alt syntax:

{
   test: /\.html$/,
   loaders: [ "html-loader?attrs=img:src img:ng-src" ]
}

Before changing your config, you can just test whether that is the reason by checking if the replacement currently works correctly for img tags with a plain static <img src="..."/>.

Assets/Images not being served · Issue #9852 · angular/angular-cli , Images GETs throw 404 error in production using Webpack and AngularJS The imported images will be then processed by the configured image-loader or  I’m getting sometimes 404 not found error when I send a stringified array of javascript objects to an API function. I have tried changing the method to send the

Instead of letting webpack parsing your templates, you might try to explicitly import your image(s) and pass it to your template.

The imported images will be then processed by the configured image-loader or url-loader.

Static image
const myImage = require('./path/to/images/image1.png');

// In component declaration 
`<img ng-src="${myImage}">`
Dynamic image

Using webpack's require.context

const pathToImages = require.context('./path/to/images', true);
const dynamicImageName = 'foo.jpg',

// In component declaration 
`<img ng-src="${pathToImages(dynamicImageName, true)}">`

CSS images with relative path not included in production build , CSS images with relative path not included in production build #4806 7.0.0-​beta.19 @ngtools/webpack 7.2.3 @schematics/angular 7.2.3 logo-pp.png:1 GET https://www.mysite.com/assets/logo-pp.png 404 I am also getting the same error and on looking under networks tab found the following  My understanding is that we can use similar approach as with css. I am not 100% sure about that and what webpack can actually do about that. Would love to have a way to bundle images in html or other suggested way to have images in html optimized. Additionally, having a sample right inside a new project template would be awesome.

Can you try below change into your index.html

<base href="./"></base>

Why do I get 404 on javascript files that are present my application , CSS images with relative path not included in production build #4806 Was getting a 404 error on the file until I changed it to I had a short look at https://​github.com/webpack-contrib/html-loader export function HttpLoaderFactory(​http: HttpClient) { return new TranslateHttpLoader( http, `${environment. When you're using Webpack, you have a really huge benefit that comes with all of your resolve statements being executed before your files are loaded into the browser. One thing that is insanely powerful is instead of using templateUrl, you can use template everywhere.

SOLUTION Let's start with

output.publicPath: '/customer_company_name/our_company_name/'

this will take care of rewriting ng-/src paths correctly as explained here.

We won't need the html-loader to parse ng-/src, the only thing needed is to always use ng-src, or the build won't be successful.

Eventually, there's no need of <base> tag and neither the initial slash in every path used to refer to images.

I'll update this answer as I improve the webpack-dist.conf.js/the whole project for the better.


No answer given worked per se, hence I'll try combinations of them since some suggestions look legit.

Eventually, if I won't be able to solve this, I'll try to drop the production path prefix /customer_company_name/our_company_name/.

How to handle 404 error in angular 6, I scaffolded the project using angular cli and I have added a couple of Why do I get 404 on javascript files that are present my application root in rel="icon" type​="image/x-icon" href="favicon.ico"> </head> <body> All the JavaScript includes in the index.html return 404 but all these That was the error. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Handling 404 errors in an Angular project, Traditional promises (using the $q Service in Angular) 31 Dec 2016 Error handling in The orange color works so well because it relates to the orange image in the 404. 9. I am having a problem getting client-side page routing to work properly. Angular 8, Angular 7, Angular 6, Angular 5 (and older) app in production incl. Missing files cause compilation errors instead of 404 errors for your users. Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. However there is an escape hatch that you can use to add an asset outside of the module system.

30 Answers from Stack Overflow to the most popular webpack , A common problem with web applications is a user landing on an invalid URI; this error, known as the venerable 404 - page not found error, is a common  With the -t argument, we define the name of the image. The second argument (".") defines the location of the Dockerfile. This command can take a while because images have to be downloaded and the angular app has to be compiled. Spinning up a Docker container from our image. To start a Docker container using our image, we use this command:

file-loader, Babel-node is a CLI tool (not meant for production use), which at first If you have issues with ElectronJS or similar and have a sort of 404… I want to load images in javascript by webpack file-loader . 5. when i type the webpack command i am getting the below error. Return Array of Configurations Nr 3: You can change your build process, found in angular.json, to automate this by adding: "baseHref": "./" To your production configuration. Obviously you can use fixed paths as well with either of these, but adding this single dot to the default uses relative paths, which I would guess is the default behavior one would expect.

Comments
  • Wild guess, but have you tried $locationProvider.html5Mode(true); to eliminate the hashbang? Also, the base tag must end with a slash and the sources must not start with a slash. As far as I can tell, this should have worked out of the box. Could you provide an angular template with img tags?
  • In the beginning, I had $locationProvider.html5Mode(true) but it made the app throw 404 errors when trying to redirect to a specific page once the app crashed (via $location.path('/'); return $window.location.reload();). I agree that it should have worked out of the box, even using the hashbang; the other thing I initially did was moving the index.* files from src/ to src/app. The base tag has already a trailing slash in its src, are you referring to something else?
  • 1. $location.path('/') doesn't work without reloading the page? 2. Have you tried moving the static files out of the src folder, and tell webpack to copy them to the desired location?
  • 1. yes, but that's the use we meant for the "redirect", probably a misuse of the term indeed 2. no since that looks I'll have the same problem, but with extra steps P.S.: I think in the previous comment you meant "the base tag is a self-closing type" thank you for the observation
  • are you deploying it on iis?
  • This looks legit, but I'm currently trying to add it and it doesn't seem to work. Since there's a lot more in play in that webpack-dist.js can you please add it to the original file together with the other parts I should retain/add to it?
  • Just use it to replace the section for "html-loader" in your loaders. If it makes no difference, then the reason is something else.
  • Well, it doesn't work per se, but I'll try it in different combinations of file-loader options and src paths