Giter Club home page Giter Club logo

file-loader's Introduction

npm node deps tests coverage chat size

file-loader

DEPRECATED for v5: please consider migrating to asset modules.

The file-loader resolves import/require() on a file into a url and emits the file into the output directory.

Getting Started

To begin, you'll need to install file-loader:

$ npm install file-loader --save-dev

Import (or require) the target file(s) in one of the bundle's files:

file.js

import img from './file.png';

Then add the loader to your webpack config. For example:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],
  },
};

And run webpack via your preferred method. This will emit file.png as a file in the output directory (with the specified naming convention, if options are specified to do so) and returns the public URI of the file.

ℹ️ By default the filename of the resulting file is the hash of the file's contents with the original extension of the required resource.

Options

name

Type: String|Function Default: '[contenthash].[ext]'

Specifies a custom filename template for the target file(s) using the query parameter name. For example, to emit a file from your context directory into the output directory retaining the full directory structure, you might use:

String

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
        },
      },
    ],
  },
};

Function

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          name(resourcePath, resourceQuery) {
            // `resourcePath` - `/absolute/path/to/file.js`
            // `resourceQuery` - `?foo=bar`

            if (process.env.NODE_ENV === 'development') {
              return '[path][name].[ext]';
            }

            return '[contenthash].[ext]';
          },
        },
      },
    ],
  },
};

ℹ️ By default the path and name you specify will output the file in that same directory, and will also use the same URI path to access the file.

outputPath

Type: String|Function Default: undefined

Specify a filesystem path where the target file(s) will be placed.

String

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          outputPath: 'images',
        },
      },
    ],
  },
};

Function

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          outputPath: (url, resourcePath, context) => {
            // `resourcePath` is original absolute path to asset
            // `context` is directory where stored asset (`rootContext`) or `context` option

            // To get relative path you can use
            // const relativePath = path.relative(context, resourcePath);

            if (/my-custom-image\.png/.test(resourcePath)) {
              return `other_output_path/${url}`;
            }

            if (/images/.test(context)) {
              return `image_output_path/${url}`;
            }

            return `output_path/${url}`;
          },
        },
      },
    ],
  },
};

publicPath

Type: String|Function Default: __webpack_public_path__+outputPath

Specifies a custom public path for the target file(s).

String

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: 'assets',
        },
      },
    ],
  },
};

Function

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: (url, resourcePath, context) => {
            // `resourcePath` is original absolute path to asset
            // `context` is directory where stored asset (`rootContext`) or `context` option

            // To get relative path you can use
            // const relativePath = path.relative(context, resourcePath);

            if (/my-custom-image\.png/.test(resourcePath)) {
              return `other_public_path/${url}`;
            }

            if (/images/.test(context)) {
              return `image_output_path/${url}`;
            }

            return `public_path/${url}`;
          },
        },
      },
    ],
  },
};

postTransformPublicPath

Type: Function Default: undefined

Specifies a custom function to post-process the generated public path. This can be used to prepend or append dynamic global variables that are only available at runtime, like __webpack_public_path__. This would not be possible with just publicPath, since it stringifies the values.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: '/some/path/',
          postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
        },
      },
    ],
  },
};

context

Type: String Default: context

Specifies a custom file context.

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              context: 'project',
            },
          },
        ],
      },
    ],
  },
};

emitFile

Type: Boolean Default: true

If true, emits a file (writes a file to the filesystem). If false, the loader will return a public URI but will not emit the file. It is often useful to disable this option for server-side packages.

file.js

// bundle file
import img from './file.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              emitFile: false,
            },
          },
        ],
      },
    ],
  },
};

regExp

Type: RegExp Default: undefined

Specifies a Regular Expression to one or many parts of the target file path. The capture groups can be reused in the name property using [N] placeholder.

file.js

import img from './customer01/file.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.png$/i,
              name: '[1]-[name].[ext]',
            },
          },
        ],
      },
    ],
  },
};

ℹ️ If [0] is used, it will be replaced by the entire tested string, whereas [1] will contain the first capturing parenthesis of your regex and so on...

esModule

Type: Boolean Default: true

By default, file-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

You can enable a CommonJS module syntax using:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              esModule: false,
            },
          },
        ],
      },
    ],
  },
};

Placeholders

Full information about placeholders you can find here.

[ext]

Type: String Default: file.extname

The file extension of the target file/resource.

[name]

Type: String Default: file.basename

The basename of the file/resource.

[path]

Type: String Default: file.directory

The path of the resource relative to the webpack/config context.

[folder]

Type: String Default: file.folder

The folder of the resource is in.

[query]

Type: String Default: file.query

The query of the resource, i.e. ?foo=bar.

[emoji]

Type: String Default: undefined

A random emoji representation of content.

[emoji:<length>]

Type: String Default: undefined

Same as above, but with a customizable number of emojis

[hash]

Type: String Default: md4

Specifies the hash method to use for hashing the file content.

[contenthash]

Type: String Default: md4

Specifies the hash method to use for hashing the file content.

[<hashType>:hash:<digestType>:<length>]

Type: String

The hash of options.content (Buffer) (by default it's the hex digest of the hash).

digestType

Type: String Default: 'hex'

The digest that the hash function should use. Valid values include: base26, base32, base36, base49, base52, base58, base62, base64, and hex.

hashType

Type: String Default: 'md4'

The type of hash that the hash function should use. Valid values include: md4, md5, sha1, sha256, and sha512.

length

Type: Number Default: undefined

Users may also specify a length for the computed hash.

[N]

Type: String Default: undefined

The n-th match obtained from matching the current file name against the regExp.

Examples

Names

The following examples show how one might use file-loader and what the result would be.

file.js

import png from './image.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'dirname/[contenthash].[ext]',
            },
          },
        ],
      },
    ],
  },
};

Result:

# result
dirname/0dcbbaa701328ae351f.png

file.js

import png from './image.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[sha512:hash:base64:7].[ext]',
            },
          },
        ],
      },
    ],
  },
};

Result:

# result
gdyb21L.png

file.js

import png from './path/to/file.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]?[contenthash]',
            },
          },
        ],
      },
    ],
  },
};

Result:

# result
path/to/file.png?e43b20c069c4a01867c31e98cbce33c9

CDN

The following examples show how to use file-loader for CDN uses query params.

file.js

import png from './directory/image.png?width=300&height=300';

webpack.config.js

module.exports = {
  output: {
    publicPath: 'https://cdn.example.com/',
  },
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext][query]',
            },
          },
        ],
      },
    ],
  },
};

Result:

# result
https://cdn.example.com/directory/image.png?width=300&height=300

Dynamic public path depending on environment variable at run time

An application might want to configure different CDN hosts depending on an environment variable that is only available when running the application. This can be an advantage, as only one build of the application is necessary, which behaves differently depending on environment variables of the deployment environment. Since file-loader is applied when compiling the application, and not when running it, the environment variable cannot be used in the file-loader configuration. A way around this is setting the __webpack_public_path__ to the desired CDN host depending on the environment variable at the entrypoint of the application. The option postTransformPublicPath can be used to configure a custom path depending on a variable like __webpack_public_path__.

main.js

const assetPrefixForNamespace = (namespace) => {
  switch (namespace) {
    case 'prod':
      return 'https://cache.myserver.net/web';
    case 'uat':
      return 'https://cache-uat.myserver.net/web';
    case 'st':
      return 'https://cache-st.myserver.net/web';
    case 'dev':
      return 'https://cache-dev.myserver.net/web';
    default:
      return '';
  }
};
const namespace = process.env.NAMESPACE;

__webpack_public_path__ = `${assetPrefixForNamespace(namespace)}/`;

file.js

import png from './image.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        loader: 'file-loader',
        options: {
          name: '[name].[contenthash].[ext]',
          outputPath: 'static/assets/',
          publicPath: 'static/assets/',
          postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
        },
      },
    ],
  },
};

Result when run with NAMESPACE=prod env variable:

# result
https://cache.myserver.net/web/static/assets/image.somehash.png

Result when run with NAMESPACE=dev env variable:

# result
https://cache-dev.myserver.net/web/static/assets/image.somehash.png

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

file-loader's People

Contributors

akx avatar alexander-akait avatar cjhanrahan avatar evilebottnawi avatar fabb avatar joshwiens avatar jungomi avatar kevinzwhuang avatar kossnocorp avatar marcusds avatar mattgurney avatar michael-ciniawsky avatar moughxyz avatar mrpoptart avatar munter avatar necolas avatar nicktho avatar rderandom avatar renestalder avatar rondonjon avatar serut avatar shama avatar simenb avatar simon04 avatar smondal avatar sokra avatar spacek33z avatar syranide avatar tedpennings avatar tstirrat15 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

file-loader's Issues

Method for specifying include paths for files (e.g. node_modules)

I have a rule in a CSS file that references a file loaded from an npm module (in node_modules) ... but I cannot find a way to have file-loader locate this file, unless I make it relative, e.g. ../../../../node_modules/module/image.png.

It would be nice if there was a way to tell file-loader to treat node_modules as an include path.

As a point of comparison, it appears that sass-loader lets you do this.

Return relative url without emiting file

This is more of a question than an issue:

I am using webpack to build both my client and server bundle, what is the most straightforward way to set up file-loader or webpack so that on the service side, it replace the require with the proper url but doesn't emit files in the output? Those are already emitted by the client build, so it's redundant.

Dead Loop In Windows

Example:

entry: ./shares/templates/app.html

{
test: /.(html|xml)$/,
loader: 'file?name=templates/[1]/[2]&regExp=([^/]+)[/\]templates/\$'
}

Default options

Hi.

Probably my use case is not popular or even this feature request should go to the webpack directly. But I want to have ability to specify default options for the file loader, e.g. set the name to [name].[ext].

I have a worker.js code which uses Web Worker interface and want to include it to the build using the file loader. Also I need to know its resulting public URL in order to spawn it. Everything seems to be perfect with file-loader, but:

  • I don't want to add {test: "worker.js", loader: "file?name=[name].[ext]"} to webpack.config.js and use just const url = require("worker.js") because then my JS is tightly coupled to build configuration - if I change the worker file name in the souces but forget about the webpack config, everything will broke
  • I don't want to set file loader options in JS file either, like this: const url = require("file?name=[name].[ext]!worker.js"), because again, my JS will be tightly coupled to the build configuration - I want to change the name based on the NODE_ENV and it would be wrong to add that logic to the common JS sources

In other words I want to be able to specify require("file!worker.js") in JS file and {file: {name: "[name].[ext]"}} somewhere in webpack.config.js

I haven't found in the documentation/webpack issues anything similar, but look for example at this PR to the babel loader. It seems to be that users do want to provide global/default options for loaders sometimes.

My feature request could be easily implemented because loaders have access to the webpack's global config but maybe I'm doing something wrong or don't understand something and would like to hear your opinion on this.

Output files to a different dir

Hello,

I am building an web app using bootstrap. I had this line to include the .css file

var Bootstrap  = require('../../node_modules/bootstrap/dist/css/bootstrap.min.css');

I would like to output the corresponding font files that bootstrap.min.css relies on to /dist/css/

Here is a simplified version of my webpack.config.js:

module.exports = {
    entry: {
        app: path.resolve(__dirname, 'app/src/index.js'),
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '../js/[name].js'
    },
    module: {
        loaders:[{
            test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
            loader: 'file-loader'
        }]

How can I config file-loader to output the font files to /dist/css instead of /dist/?

Thank you!

Ignore file output

Hi

I love this plugin but in a isomorphic app you don't want the server-side app to generate the images, but you still want the correct url of the resource.

I searched but I could not find any solution, so I forked this module and then just deleted the line that saves the file.

I published it as ignore-file-loader. https://github.com/kevinsimper/ignore-file-loader/

Causes Webpack to build empty JS bundle with OccurrenceOrderPlugin

When I'm using this loader with the OcurrenceOrderPlugin, my outputted JS bundle becomes empty.

Here's my config file:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'cheap-module-source-map',
    entry: {
        javascript: path.resolve(__dirname, 'src/index.jsx'),
        html: path.resolve(__dirname, 'src/index.html')
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['', '.js', '.jsx'],
    },
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
    ],
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.html$/,
                loader: 'file',
                query: {
                    name: '[name].[ext]'
                }
            }
        ]
    }
}

If I remove the usage of the loader and the entry point for it, my compiles js is ~700kB. If I add it back in, it compiles down to 1 kB and is effectively empty (no contents besides code pointing to the source map).

I wasn't sure if this is a file-loader problem or a webpack problem, but I couldn't find any similar issues there, so I presume it is file-loader related.

file-loader works in require but not configure

The file loader works from a require statement in a js file

require('file!./../fonts/olivier.ttf');

but not when the webpack config is setup to use the file loader on ttf files

module.exports = {
  plugins: [
    new ComponentPlugin(),
    new webpack.ProvidePlugin({
      "_": "lodash",
      $: "jquery",
      jQuery: "jquery",
      "windows.jQuery": "jquery"
    })
  ],
  loaders: [
    { test: /\.ttf$/, loader: "file" },
    { test: /\.css$/,
      loader: "style-loader!css-loader" },
    { test: /\.less$/,
      loader: "style-loader!css-loader!less-loader"
    }
  ]
};

This setup gives this error:

ERROR in ./public/fonts/olivier.ttf
Module parse failed: /Users/rmil19/workspace/metric/public/fonts/olivier.ttf Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./public/js/main.js 5:0-33

Dynamic contexts & naming

Hey there, thanks for all the hard work.

I was wondering if it was possible to have control over the naming when using the file-loader width dynamic requires.

This code
path = require 'themes/' + themeCode + '/locale/' + languageCode + '.json'
With this dir structure
/src/themes/civic/locale/en.json
With this config
{test: /\.json$/, loader: "file-loader"}
Results in
/build/03f272c55f8da7ff3616a17654816467.json
With this config instead
{test: /\.json$/, loader: "file-loader?name=[path][name].[ext]"}
It results in
/build/src/themes/civic/locale/en.json
I was curious if there was a way to get a result such as
/build/locales/civic/en.json
perhaps there is away to get the context variables
{test: /\.json$/, loader: "file-loader?name=locales/[context[0]]/[context[1]].[ext]"}

Thanks for any feedback

otf font not being loaded correctly

Here's my config:

{
      test: /\.(otf|eot|woff|woff2|ttf|svg|png|jpg)$/,
      loader: 'file-loader?limit=30000&name=[name]-[hash].[ext]'
    }

When I require a .ttf font everything works fine. Then trying to use .otf, no error is thrown, but the font simply doesn't load.

Any help would be greatly appreciated. Thanks!

How to deal with relative public path

I set a relative public path in outputs

output: {
  path: path.join(__dirname, 'www/static'),
  filename: '[hash].bundle.js',
  publicPath: './'
}

Then the file structure is like

www
  |-- static
          | -- bundle.js
          | -- some-image.png
          | -- some-other-image.png
          | -- style.css
  |-- index.html

When i require image in css, i works fine.

But when i require image in some js, the url is wrong.

const url = require('path/to/some-image.png');
// the url will be 'some-image.png'
// but this url will be used in index.html (through react)

Any one can help me with it? Thanks.

Duplicated output directory

I'm trying to extract font files inside my css/ output directory but when the page loads is looking for the files inside css/css/ directory.

I don't know what i'm doing wrong but I can't figure it out how to get rid of that duplicated directory.

This is my webpack config file:

const BrowserSyncPlugin = require("browser-sync-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: "./src/js/app.js",
  output: {
    path: __dirname + "/bin/",
    filename: "js/main.js"
  },
  module: {
    preLoaders: [
      {test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/},
      {test: /\.js$/, loader: "jscs-loader", exclude: /node_modules/},
    ],
    loaders: [
      {test: /\.js$/, loader: "babel-loader", exclude: /node_modules/},
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader",
        "css-loader?sourceMap" +
        "!autoprefixer-loader?browsers=last 2 version" +
        "!sass-loader?outputStyle=expanded&sourceMap&sourceMapContents")
      },
      {
        test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        loader : "file-loader?name=./css/[name].[ext]",
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("css/main.css", {
      allChunks: true
    }),
    new BrowserSyncPlugin({
      host: "localhost",
      port: 3000,
      server: {baseDir: ["./bin"]},
      files: ["bin/*.html"]
    })
  ]
};

And this is where the index files is looking for the font files:

http://localhost:3000/css/css/huge_agb_v5-webfont.woff

[this.emitFile] Corrupted font files (.woff|.woff2|.eot|.ttf)

Like here #36
I can literally copy this issue description.
I am trying to import font-awesome into my project.
And I have these warnings in console, but reboot does not help me. :)

Failed to decode downloaded font: http://localhost:8080/assets/fonts/fontawesome-webfont.woff2?d396b5051cc2b597286ba6be02bd1327
OTS parsing error: Failed to convert WOFF 2.0 font to SFNT
Failed to decode downloaded font: http://localhost:8080/assets/fonts/fontawesome-webfont.woff?1a5f7cb348ebfe17ee45a78fac811c1d
OTS parsing error: incorrect file size in WOFF header
Failed to decode downloaded font: http://localhost:8080/assets/fonts/fontawesome-webfont.ttf?06d05732fc1f7dbb1bf6f9d4b2b895f4
OTS parsing error: incorrect entrySelector for table directory

I've tried everything (for example - url-loader) but it does not work.
And when I use this lib directly - it works very well.

I hope you can help me, this is my first project with Webpack and probably I have made some silly mistake.

My config file (it is part of angular-kick):

var config = {

  // set the context (optional)
  context: __dirname + '/app',
  entry: 'app.js',

  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  },

  // enable loading modules relatively (without the ../../ prefix)
  resolve: {
    root: [__dirname + '/app']
  },

  module: {
    preLoaders: [
      {
        test: /\.*/,
        loaders: ['env-replace?prefix=@@&file=' + __dirname + '/environments.json']
      }
    ],
    loaders: [
      // Transpile ES6 and annotate AngularJS dependencies
      { test: /\.js$/, exclude: /node_modules/, loaders: ['ng-annotate', 'babel'] },

      // SCSS
      { test: /\.s?css$/, loader: 'style!css!autoprefixer!sass?' + 'includePaths[]=' + __dirname + '/app'},

      //JSON
      { test: /\.json$/, loader: 'json' },

      // Fonts and images
      { test: /\.woff(\?.*$|$)/, loader : 'file-loader?name=/assets/fonts/[name].[ext]?[hash]' },
      { test: /\.woff2(\?.*$|$)/, loader : 'file-loader?name=/assets/fonts/[name].[ext]?[hash]' },
      { test: /\.ttf(\?.*$|$)/, loader : 'file-loader?name=/assets/fonts/[name].[ext]?[hash]' },
      { test: /\.eot(\?.*$|$)/, loader : 'file-loader?name=/assets/fonts/[name].[ext]?[hash]' },
      { test: /\.svg(\?.*$|$)/, loader : 'file-loader?name=/assets/fonts/[name].[ext]?[hash]' },
      { test: /\.(png)$/, loader: 'url?mimetype=image/png' },

      // Create AngularJS templates from HTMLs
      {
        test: /\.html$/,
        loaders: ['ngtemplate?relativeTo=' + __dirname + '/app', 'html']
      }
    ]
  },

  devServer: {
    contentBase: './app',
    noInfo: false,
    hot: true,
    historyApiFallback: true
  }

};

if (process.env.NODE_ENV === 'development') {
  config.devtool = '#inline-source-map';
}

module.exports = config;

New release?

@sokra I see you merged a pile of PRs last night (including mine, #64, thanks). Do you have an ETA for a new release of the package? NPM tells me 0.8.5 was released seven months ago.

svg is not being loaded when using webpack-dev-server

I'm not sure if this issue is with the file-loader or webpack-dev-server the bottom line is my svg that I use for showing a logo by setting it as a background on a css selector ... is not working when using webpack-dev-server. The css is getting compiled, the file (based on the console output) also seems to get bundled, but then when I load my page it is as if the css was referring to a non existent svg file.

The same svg / css and config but using regular webpack works and outputs the svg in my public/assets holder with the hash name.

my.scss

    .logo--mylogo {
      background: url("../../../svg/mylogo.svg") no-repeat left top;
      background-size: contain;
    }

using image-webpack-loader

                {
                    test: /\.(jpe?g|png|gif|svg)(?:\?.*|)$/i,
                    loaders: [
                        'file?hash=sha512&digest=hex&name=[hash].[ext]',
                        'image-webpack'
                    ]
                },

using file-loader

{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},

webpack.config

    var webpackConfig = {
        context: jsSrc,

        resolve: {
            extensions: ['', '.js', '.coffee', '.scss', '.less', '.css'],
            modulesDirectories: [node_dir, bower_dir, components_dir]
        },

        plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoErrorsPlugin(),
            new webpack.DefinePlugin({
                ENVIRONMENT: JSON.stringify(process.env.NODE_ENV || env)
            }),
            new ExtractTextPlugin('styles/[name].css', {
                disable: false,
                allChunks: true
            }),
        ],

        module: {
            loaders: [
                {
                    test: /\.(jpe?g|png|gif|svg)(?:\?.*|)$/i,
                    loaders: [
                        'file?hash=sha512&digest=hex&name=[hash].[ext]',
                        'image-webpack'
                    ]
                },
                {
                    test: /\.s?css$/,
                    exclude: /.*\.min.css/,
                        'css-loader?' + JSON.stringify({ sourceMap : shouldSourceMap })
                        + '!sass-loader?' + JSON.stringify({ includePaths: bourbonPaths, sourceMap : shouldSourceMap })
                },
                {
                    test: /\.css$/,
                    loader: ExtractTextPlugin.extract('css-loader?' + JSON.stringify({ sourceMap: shouldSourceMap }))
                }
            ],
            noParse: [],
        }
    }


    webpackConfig.entry = {
        vendor: [
            'webpack-dev-server/client?http://localhost:8081',
            'webpack/hot/only-dev-server',
            './vendor.js'
        ],
        app: [
            'webpack-dev-server/client?http://localhost:8081',
            'webpack/hot/only-dev-server',
            './app.js'
        ]
    }

    webpackConfig.output = {
        path: destAssetsAbsPath,
        filename: env === 'production' ? '[name]-[hash].js' : '[name].js',
        publicPath: '/assets/',
        chunkFilename: "/js/[id].js"
    }

webpack task

gulp.task("webpack:dev-server", function(callback) {
  var devServer;

  new WebpackDevServer(webpack(config), {
    publicPath: '/assets/',
    hot: true,
    quiet: false,
    noInfo: false,
    stats: { colors: true },
    headers: { "X-Custom-Header": "yes" },
    historyApiFallback: true
  }).listen(8081, 'localhost', function (err, result) {
        if (err) {
          console.log(err);
        }
        callback()

        console.log('Listening at localhost');
      });
});

output console
I see the file built in both cases.
[68] ./resources/assets/svg/logo/mylogo.svg 81 bytes {0} [built]

Sub Directory entry points

I am using multiple entry points to create my modules. My index.html files for each entry point are in different paths. I did not want to separate my modules into new webpack projects, but I need them to be able to stand alone later as their own root entry.
The entries are setup like the following:

  • ./main.js (./index.html)
  • ./admin/main.js (./admin/index.html)
  • ./anotherentry/main.js (./anotherentry/index.html)

I have actually solved any public path issues during webpack-dev-server by setting

  • output.publicPath = '/' when running the webpack-dev-server
  • output.publicPath = '' when running webpack

The problem I have with file-loader now is that it always emits the file to a relative path to the context and also sets the url to the path from the context root which means the path points to the incorrect place for the entry points in the sub directories.

Here is how I think file-loader should handle the path of the url's.

  • have an emitUrl based on the options.context
  • have a url based on query.context || this.options.context as the root and pass context in parameters if in a sub directory. I am not sure there is a way to know if your entry is in your current directory.
  • if the public path is absolute (i.e. this.options.output.publicPath.substr(0,1) === '/') then the emitUrl and url are the same and paths do not need to be different

If you think I am going down the wrong road with this, please let me know. Otherwise, I think I could put together a PR to show you what I mean.

Allow access to [parent] variable

I'd really want access to the name of the parent require. So if I require a module bootstrap and it does:

require('abc.css')

I can then control the output of that file and have it be:

somedir/bootstrap/abc.css

I'd imagine it's something like:

?name=somedir/[parent]/[name].css

Specify what to hash

I'd like to be able to specify what to mangle through the hash function in order to get the [hash]. In my specific case, I want to hash [path][name]. I can well imagine an additional query parameter like hashSource which works like name but with the addition of [content], to which it defaults.

Rationale: we're building different versions that are served based on the request origin, but using the same js bundle (and server side code!), but with different file contents (e.g. different images at logo.png). If we were to hash the content, the different file had a different hash, and we could not map it from the one the js bundle requested. We don't want to use path in production either because it gives away our file structure. Hence we'd like to hash the path.

Similar, alternative approach: add one more parameter into the hash brackets (like which encoding to use) that specifies what variable (path, name, content,...) to hash.

Allow option for relative URLs

I have a scenario where I need the file-loader to return the url relative not absolute to the output path. Please allow an option to do this. Currently, I'm filtering out the pre-prended '/' with sed.

Unexpected character

Hi

I'm very new to webpack and loading files so probably I'm completely off and please correct me.
I have loaded dozens of png images in my site without problem.
With one (access2.png) I constantly get this error message:

> [email protected] start C:\Users\alex\gs
> webpack-dev-server

C:\Users\alex\gs\node_modules\babel-core\lib\babel\transformation\file\index.js:600
      throw err;
            ^
SyntaxError: C:/Users/alex/gs/images/access2.png: Unexpected character '´┐¢' (1:0)
> 1 | ´┐¢PNG
    | ^
  2 | ←[7m→←[27m
  3 | ←[7m

npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "s
tart"
npm ERR! node v0.12.3
npm ERR! npm  v2.9.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `webpack-dev-server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'webpack-dev-server'.
npm ERR! This is most likely a problem with the gs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack-dev-server
npm ERR! You can get their info via:
npm ERR!     npm owner ls gs
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\alex\gs\npm-debug.log

I can link this file without loading it over webpack and it works fine.

Is this a problem with file-loader?

I attached the image file below.
The Image is loaded here: https://github.com/barbalex/gs/blob/master/src/pages/public.js#L5
Loading is configured here: https://github.com/barbalex/gs/blob/master/webpack.config.js#L35-40

Alex
access2

Add note about JSX usage

Just spent the last few hours (more than a few?) on this problem and it was entirely avoidable but I haven't seen any docs on it.

If you are using JSX (and therefor probably babel-loader) you do not need to use file-loader or url-loader for img tags in the JSX, its somehow already handled by babel. I somehow knew JSX was handled by babel-loader, but I have no idea how that came about, but as a bonus it handles the stuff of file-loader.

I eventually figured this out because I was doing this, which seems to be the right way to do it

<img src={require('../../assets/images/image.png')} />

But having png files handled by both babel-loader and file-loader meant the browser was displaying a broken image, which I eventually downloaded and opened, and instead of ugly binary, it was this :)

module.exports = __webpack_public_path__ + "265a6261bff86f8c7bc3c98c5eba3583.png"

How to specify a directory (not a file)

Right now I have the following, with more to come.

require("file?name=[path][name].[ext]&context=./src!./img/logo.png");
require("file?name=[path][name].[ext]&context=./src!./img/bg.png");
require("file?name=[path][name].[ext]&context=./src!./img/envelope.png");
require("file?name=[path][name].[ext]&context=./src!./img/camera-black.png");

And this creates the img/ folder in the build folder as expected and populates it with the four files.

The reason we do this is, because the folder is shared buy a number of customers who develop their own custom modules and don't often use webPack - but do put their files / folders into the src/img folder for automated building.

So there are things like

 /img/cust1/*.*
 /img/cust2/*.*
 /img/cust3/*.*
 /img/cust4/*.*

What i was trying to do was bundle them in one go when we build the site / tenants rather than having to pipe all the directory listing into a file and then globally replace parts of the path with the requires section and run macros to fix the line endings. I have to do this every time a new file is added, so it just gets done manually as part of the build every time regardless - just in case there is another files or a file that been removed

I tried doing all of these but I get must be a 'file' or 'directory' errors.

require("file?name=[path][name].[ext]&context=./src!./img/**");
require("file?name=[path][name].[ext]&context=./src!./img/**/");
require("file?name=[path][name].[ext]&context=./src!./img/**/*.png");
require("file?name=[path][name].[ext]&context=./src!./img/");
require("file?name=[path][name].[ext]&context=./src!./img");
require("file?name=[path][name].[ext]&context=./src!./cust1/*.*");
require("file?name=[path][name].[ext]&context=./src!./cust1/");

How do you specify a "directory" like the error messages says you can ?

Why does file loader add an "_" to output directory paths?

I've tried searching everywhere I can but cannot figure out why File-loader, or more specifically the loader-utils, keep adding an "" directory to which it adds all my images loaded from CSS. Why is this happening? Why can I not use the same path from my /src directory without adding an "" directory at the top?

Loading jpg files results in corrupted export, but only when the ext is in lowercase

I think my configuration is quite minimal with only ts-loader and file-loader for files.

Example:

const CUTE_AVATAR = require('path/to/image.jpg');

results in corrupted file, but

const CUTE_AVATAR = require('path/to/image.JPG');

does not. Both point to the same image, image's original extension is in lowercase (maybe doesn't matter since OS X).

It also results in different [sha512:hash:base64:7] between the lowercase and the uppercase one.

png files are not affected. Only jpg.

Loaders config below if needed.

loaders: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader'
            },
            {
                test: /\.(jpg|png)$/i,
                loader: 'file?name=[sha512:hash:base64:7].[ext]'
            }
        ]

Any ideas? Thanks.

Add ability to copy over a whole directory with random files

I am trying to copy a bunch of static files (can be any type including binaries, so not just js/css/html, but like .bin/.obj etc.) from the source folder to output directory. I cannot find a way to properly do this with the file loader, unsure if it is possible:

// src.js
import '/path/to/third-party/vendor/directory';
// webpack.config.js
{
    test: path.join(__dirname, '/path/to/third-party/vendor/directory'),
    loader: 'file-loader?name=[path][name].[ext]'
}

Is it possible with the file loader? I looked at webpack/webpack#525 however the method in that doesn't seem to work unless I am doing something wrong.

Unable to install in windows...

There's an issue with the BigNum package, which requires OpenSSL header libraries for windows... honestly, is this REALLY needed as a dependency? Isn't there a JS based solution that can work for the needs of this module?

> node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" configure build
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
  bignum.cc
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xlocale(337): warning C4530: C++ exception handler
 used, but unwind semantics are not enabled. Specify /EHsc [D:\src\local\cc5-website\node_modules\file-loader\nod e_modules\bignum\build\bignum.vcxproj]
D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum\node_modules\nan\nan.h(1185): warning C4267 : '=' : conversion from 'size_t' to 'int', possible loss of data [D:\src\local\cc5-website\node_modules\file-load er\node_modules\bignum\build\bignum.vcxproj]
D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum\node_modules\nan\nan.h(1202): warning C4267 : '=' : conversion from 'size_t' to 'int', possible loss of data [D:\src\local\cc5-website\node_modules\file-load er\node_modules\bignum\build\bignum.vcxproj]
D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum\node_modules\nan\nan.h(1215): warning C4267 : 'initializing' : conversion from 'size_t' to 'int', possible loss of data [D:\src\local\cc5-website\node_module s\file-loader\node_modules\bignum\build\bignum.vcxproj]
D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum\node_modules\nan\nan.h(1229): warning C4267 : 'initializing' : conversion from 'size_t' to 'int', possible loss of data [D:\src\local\cc5-website\node_module s\file-loader\node_modules\bignum\build\bignum.vcxproj]
D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum\node_modules\nan\nan.h(1318): warning C4244 : 'return' : conversion from 'intptr_t' to 'int', possible loss of data [D:\src\local\cc5-website\node_modules\fi le-loader\node_modules\bignum\build\bignum.vcxproj]
..\bignum.cc(9): fatal error C1083: Cannot open include file: 'openssl/bn.h': No such file or directory [D:\src\l ocal\cc5-website\node_modules\file-loader\node_modules\bignum\build\bignum.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:810:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "build"
gyp ERR! cwd D:\src\local\cc5-website\node_modules\file-loader\node_modules\bignum
gyp ERR! node -v v0.10.31
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok
npm WARN optional dep failed, continuing [email protected]
[email protected] node_modules\file-loader

Outputting wrong file name for image

https://github.com/JellyKid/TwitchTV_FCC

You can find my webpack config there. I'm importing an image in app/components/Channel.jsx. File-loader creates an empty image file and URL string passed to the URL variable. Then it creates the correct file with a totally different hash. I can't seem to get it to give me the correct url or figure out why it's creating an empty image with the correct name.

For example, if I build my project I get two png files.
One 1KB PNG b28d947a261b18ffe4e9740a151b60b5.png and a second 4KB PNG aadf7e0813a755cc519342de5ce91041.png, but file-loader returns the string to the first blank image. File loader should really only be creating one image, so where the second one is coming from, I'm baffled.

file-loader seems to corrupt font files (.woff .woff2 .eot .ttf)

I'm extracting font files from CSS into my dist/ folder with the file-loader. That works nicely. However the file-loader seems to corrupt the font files. No browser can display them anymore.

When I copy the original font files manually into my dist/ folder, everything works.

These are the warnings I'm getting from the latest version of Chrome:

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/dist/fonts/MaterialIcons-Regular-5be9da5f5fe772cae17b56df1cf150a7.woff2
kitchen-sink.html:1 OTS parsing error: Failed to convert WOFF 2.0 font to SFNT

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/dist/fonts/MaterialIcons-Regular-cd63a3a9169fbd408105e71820482aa1.woff
kitchen-sink.html:1 OTS parsing error: incorrect file size in WOFF header

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/dist/fonts/MaterialIcons-Regular-9679b709fae34447e6ba1362138a63f1.ttf
kitchen-sink.html:1 OTS parsing error: incorrect entrySelector for table directory

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/dist/fonts/socicon-fb368d36440f2c7fe9a87558cb3e0c58.woff2
kitchen-sink.html:1 OTS parsing error: Size of decompressed WOFF 2.0 is set to 0

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/dist/fonts/socicon-c1a3e19822251c78c74275e8820687a7.woff
kitchen-sink.html:1 OTS parsing error: incorrect file size in WOFF header

kitchen-sink.html:1 Failed to decode downloaded font: http://localhost:8888/fonts/socicon-a59005d8108d177950adabbfd9ff2ff7.ttf
kitchen-sink.html:1 OTS parsing error: FFTM: invalid table offset

I also tried setting ?mimetype=application/font-woff (etc) and using the url-loader to inline the fonts in the CSS all with the same result as above.

I hope you can help me, this is my first project with Webpack, I really like it so far! Great work!

Outputting compiled html to file?

I intend to use hashes everywhere I can with webpack, because it solves so many problems. However, we want to serve the root html code as a static file (and not by node).

I looked around a bit and found the html-loader and it's exactly what I want when paired with the file-loader, but it outputs code that has to be evaluated to make sense. Just thinking out loud, would it be possible to have some kind of eval-loader that would evaluate the code and return the result?

(I apologize if I overlooked something, it's hard to get a great overview of the endless possibilities :))

Require image in jade

Hi all!

I using Webpack + Jade + Angular2 + Typescript . When i set the loaders
{ test: /.(png|jpe?g|gif|svg|ico)$/, loader: "file-loader?name=images/[sha512:hash:base64:8]-[name].[ext]?[hash]" }

for img

background-image: url('resources/ag.svg');

and run build, image path in .scss file is changed ok, EX:
background-image: url(http://localhost:8080/images/2eVc70I_-ag.svg?cde7ddf2af6be42d532cdbea94f8bf5c);

but in the .jade file i set img path as
img(src="/resources/img/abc.png")

and then i build, the image path not changed keep as

i can not using this line in jade img(src="require('/resources/img/abc.png')")

Thanks!

Not able to copy an image file

I tried to copy an image from my folder static into the dist output like this

require('file?name=foo.png!./static/foo.png')

But the image always ended up being 80bytes and not the image as it should be (original is 90k). Could there be a clash when .png is also defined in a loader config?

My webpack image loader is configured like this

{
        test: /\.(png|jpe?g)$/,
        loaders: [
          'url?limit=10000',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false',
          'image-maxsize-webpack?useImageMagick=true'
        ]
      }

Module are relative to __webpack_require__.p instead of __webpack_public_path__

I'm using 0.8.5

My image is compiled as module.exports = __webpack_require__.p + "60247a30f60ff8bf38641abc039d435a.png" inside the generated source code. But there's no publicPath setup in the webpack config.

Given this, I would've expected the path to be relative to __webpack_public_path__ (reading the code of this plugin is also what I'm lead to believe https://github.com/webpack/file-loader/blob/master/index.js#L17).

I'm wondering if a step further down the compilation is actually changing __webpack_public_path__ to __webpack_require__.p

Emit a new chunk for the file

It looks like the file-loader does not emit a new chunk for the generated file.

This breaks some compatibility with plugins that perform actions on specific chunks. Specifically the html-webpack-plugin.

emitFile is required from module system

Curious why an error is thrown for this. Should it not fail silently (or still warn), but at least return the same path to the file and just not call emitFile?

I noticed the issue raised over at enhanced-require: webpack/enhanced-require#3, and I understand why, but here's my use case:

I'm using webpack via the Node.js API to server-side render a site built heavily with React. In order to benefit from the server-side rendering, the client side code must render the same thing when the React component is mounted to the DOM. Using require('url!mylogo.png'); renders the logo fine but where emitFile can't be used I need to at least get the same path to the image for the React client side rendering to match the prerender from the server.

In order to get this to work properly I amended the loader as follows:

  • Remove error thrown when no emitFile present (ie: via node api / enhanced-require)
  • Check for emitFile and don't call it if it's not there

I also had to set __webpack_public_path__ at runtime if it was not set to avoid an issue there.

Then it works. Hopefully you understand the React bit. I can see why you might want to alert the user but for my purposes it helps if the loader fails silently when emitFile is not present.

how to set webpack config with materialize?

Sorry to bother, because it could be the local problem. But it has been bothered me for days.

here is my webpack config:

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

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: 'dist/',
        filename: 'build.js'
    },
    resolveLoader: {
        root: path.join(__dirname, 'node_modules'),
    },
    module: {
        loaders: [
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel?{"presets":["es2015"]}',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract(
                    "style-loader", "css-loader?sourceMap!postcss-loader")
            },
            {
                test: /\.(jpg|png|gif)$/,
                loader: "file-loader?name=images/[hash].[ext]"
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&minetype=application/font-woff"
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "file-loader"
            }
        ]
    },
    vue: {
        loaders: {
            css: ExtractTextPlugin.extract("css"),
        }
    },
    plugins: [
        new ExtractTextPlugin("style.css", {
            allChunks: true,
            disable: false
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
        })
    ],
    devtool: '#eval-source-map'
}

and my main.js:

import './libs/materialize/js/materialize.js'
import './libs/materialize/css/materialize.css'

everything is fine, but when I check out the console of chrome, it tells me this:

localhost/:13 GET http://localhost:3000/dist/dist/2751ee43015f9884c3642f103b7f70c9.woff2 
localhost/:13 GET http://localhost:3000/dist/dist/ba3dcd8903e3d0af5de7792777f8ae0d.woff 
localhost/:13 GET http://localhost:3000/dist/dist/df7b648ce5356ea1ebce435b3459fd60.ttf 

Motivation for using file/url-loader

I'm kind of a newbie to url/file-loader and webpack in general. Just wanted to know, what is the advanges of using file loader against just "sourcing" as usual?
i.e. <img src={include(./logo.png)} > VS <img src="path/to/assets/logo.png" >
Also is there a way avoid using ".. /.. /.. /logo.png" if I want to keep all my assets in one folder on the project's root?
Thanks!

Change filename/extension in previous loader

Hi @sokra!

I have writting new loader, which will be replace non-alpha png files to jpg (due image size optimization)
So, could you help me, please, to find a way to change the resource extension.

I have tried to do it in a loader as follows:

this.resourcePath = this.resourcePath.replace(/.png$/,'.jpg');
this.resource = this.resource.replace(/.png$/,'.jpg');

but, file-loader still emits '*.png' file...

And as usual, thank you in advance!)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.