Search code examples
javascriptwebpackcommonjswebpack-file-loader

Webpack - Copy images files


I'm currently using Webpack to pack our Angular2 application and i'm facing a problem.

I've read several documentations but I can't achieve how to copy some files in my output directory using the file loader.

Here is my current file hierarchy :

config
  | - webpack.common.js   
app        
  |- static
      | - css
           | - ...
      | - fonts
           | - ...
      | - img
           | - someimage.png
           | - anotherimage.png
  |- main.ts

and the (full) webpack.common.js :

var path = require("path")
var webpack = require("webpack")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {    
    entry: { 
      app: './app/main.ts',
    },
    output: {
        filename: 'js/[name].js',
        path:'./built',
        chunkFilename: 'bundles/[id].chunk.js'
    },


    module: {
        loaders: [
        {
            test: /\.ts$/,
            loader: 'ts',
            exclude:'./out/'
        },
        {           
             test: /\.(jpe?g|png|gif|svg)$/i,
             include: [
                 path.resolve(__dirname, '/app/static/img/'),
              ],
             loader: 'file?name=[path][name].[ext]&context=./src',

        }
        ]
    },

     resolve: {
         extensions: ['', '.js', '.ts', '.gif']
    },


     plugins: [
         new HtmlWebpackPlugin({
             template: './index.html'
         })
    ]
}

To execute webpack I play the command :

webpack --config Config/webpack.common.js  --bail

The ts file are correctly transpilled into javascript and copied into the output directory, the index.html file is also present but there is none of my image files.

I think there is something wrong in my configuration file but I can't see what. I'm banging my head on it fore many hours so any help will be much appreciated.

Thank you


Solution

  • You should use url-loader to load images. Sample code is given below.

    {
      module: {
        loaders: [
          { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url?limit=10000!img?progressive=true' }
        ]
      }
    }
    

    Are you referring the gif files or corresponding css/sass files inside your entry js file.

       entry: { 
          app: './app/main.ts',
        }
    

    Webpack will load all the files which have a reference in the entry point. If all your files are not in one entry point. Then you can add multiple entry points as shown below.

       entry: { 
          app: './app/main.ts',
          image: './app/something.ts'
        }
    

    Also, i would put webpack.config.js file directly in the root directory to have better access to the whole ecosystem. Try moving it from config folder to root folder.