Giter VIP home page Giter VIP logo

url-loader's Introduction

npm node deps tests chat size

url-loader

DEPREACTED for v5: please consider migrating to asset modules.

A loader for webpack which transforms files into base64 URIs.

Getting Started

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

$ npm install url-loader --save-dev

url-loader works like file-loader, but can return a DataURL if the file is smaller than a byte limit.

index.js

import img from './image.png';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
            },
          },
        ],
      },
    ],
  },
};

And run webpack via your preferred method.

Options

Name Type Default Description
limit {Boolean|Number|String} true Specifying the maximum size of a file in bytes.
mimetype {Boolean|String} based from mime-types Sets the MIME type for the file to be transformed.
encoding {Boolean|String} base64 Specify the encoding which the file will be inlined with.
generator {Function} () => type/subtype;encoding,base64_data You can create you own custom implementation for encoding data.
fallback {String} file-loader Specifies an alternative loader to use when a target file's size exceeds the limit.
esModule {Boolean} true Use ES modules syntax.

limit

Type: Boolean|Number|String Default: true

The limit can be specified via loader options and defaults to no limit.

Boolean

Enable or disable transform files into base64.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: false,
            },
          },
        ],
      },
    ],
  },
};

Number|String

A Number or String specifying the maximum size of a file in bytes. If the file size is equal or greater than the limit file-loader will be used (by default) and all query parameters are passed to it.

Using an alternative to file-loader is enabled via the fallback option.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
            },
          },
        ],
      },
    ],
  },
};

mimetype

Type: Boolean|String Default: based from mime-types

Specify the mimetype which the file will be inlined with. If unspecified the mimetype value will be used from mime-types.

Boolean

The true value allows to generation the mimetype part from mime-types. The false value removes the mediatype part from a Data URL (if omitted, defaults to text/plain;charset=US-ASCII).

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              mimetype: false,
            },
          },
        ],
      },
    ],
  },
};

String

Sets the MIME type for the file to be transformed.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              mimetype: 'image/png',
            },
          },
        ],
      },
    ],
  },
};

encoding

Type: Boolean|String Default: base64

Specify the encoding which the file will be inlined with. If unspecified the encoding will be base64.

Boolean

If you don't want to use any encoding you can set encoding to false however if you set it to true it will use the default encoding base64.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              encoding: false,
            },
          },
        ],
      },
    ],
  },
};

String

It supports Node.js Buffers and Character Encodings which are ["utf8","utf16le","latin1","base64","hex","ascii","binary","ucs2"].

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              encoding: 'utf8',
            },
          },
        ],
      },
    ],
  },
};

generator

Type: Function Default: (mimetype, encoding, content, resourcePath) => mimetype;encoding,base64_content

You can create you own custom implementation for encoding data.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|html)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              // The `mimetype` and `encoding` arguments will be obtained from your options
              // The `resourcePath` argument is path to file.
              generator: (content, mimetype, encoding, resourcePath) => {
                if (/\.html$/i.test(resourcePath)) {
                  return `data:${mimetype},${content.toString()}`;
                }

                return `data:${mimetype}${
                  encoding ? `;${encoding}` : ''
                },${content.toString(encoding)}`;
              },
            },
          },
        ],
      },
    ],
  },
};

fallback

Type: String Default: 'file-loader'

Specifies an alternative loader to use when a target file's size exceeds the limit set in the limit option.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              fallback: require.resolve('responsive-loader'),
            },
          },
        ],
      },
    ],
  },
};

The fallback loader will receive the same configuration options as url-loader.

For example, to set the quality option of a responsive-loader above use:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              fallback: require.resolve('responsive-loader'),
              quality: 85,
            },
          },
        ],
      },
    ],
  },
};

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: 'url-loader',
            options: {
              esModule: false,
            },
          },
        ],
      },
    ],
  },
};

Examples

SVG

SVG can be compressed into a more compact output, avoiding base64. You can read about it more here. You can do it using mini-svg-data-uri package.

webpack.config.js

const svgToMiniDataURI = require('mini-svg-data-uri');

module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              generator: (content) => svgToMiniDataURI(content.toString()),
            },
          },
        ],
      },
    ],
  },
};

Contributing

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

CONTRIBUTING

License

MIT


url-loader's People

Contributors

alexander-akait avatar andrewraycode avatar austinpray avatar bebraw avatar billyjanitsch avatar cap-bernardito avatar coryhouse avatar dayyeung avatar eecolor avatar eslamhiko avatar evilebottnawi avatar insin avatar jajaperson avatar jeff-tian avatar joshuakgoldberg avatar joshwiens avatar kevinzwhuang avatar mattgurney avatar michael-ciniawsky avatar pimm avatar romanyanke avatar shama avatar shellscape avatar simon04 avatar sokra avatar spacek33z avatar thelarkinn avatar threequartersjohn avatar vivcogit avatar wibron 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

url-loader's Issues

Reduce package size

Do you want to request a feature or report a bug?

Chore.

What is the current behavior?

Contain .github template.

What is the expected behavior?

Don't contain .github template.

If this is a feature request, what is motivation or use case for changing the behavior?

Reduce package size

Please mention other relevant information such as your webpack version, Node.js version and Operating System.

Not required.

peerDependencies will be deprecated in [email protected]

npm WARN peerDependencies The peer dependency file-loader@* included from url-loader will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
npm WARN peerDependencies The peer dependency sinon@* included from karma-sinon will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.

I’m using webpack and want to say thank you for this "url-loader" package, that’s why I don’t want it to be broken with [email protected]. Can we get rid off peerDeps?

Loading dynamic image in webpack

I am using Angular with Webpack (with loaders like file-loader, url-loader etc.)
Now, I want to load image which is being served through http.

The build was successful, when I used require('./imgs/profile.png')
But when I used tried say E.g. require('http://myserver.com/images/profile.png') the build failed.

Now, the problem is my images are not there in local environment instead they are there on some 3rd party server say e.g. AWS S3.

How to achieve this? Below is my webpack.config.js

'use strict';

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

var config = {
  entry: './src/myapp.js',

  output: {
    path: './dist/',
    filename: 'myapp.min.js'
  },

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

  module: {
    loaders: [{
      test: /\.js?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['es2015']
      }
    }, {
      test: /\.(jpg|jpeg|png|gif|svg)$/i,
      loader: 'file'
    }, {
      test: /\.(html)$/i,
      loader: 'file?name=[name].[ext]',
      include: [
        path.resolve(__dirname, 'src', 'app')
      ]
    }, {
      test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: "file"
    }, {
      test: /\.less$/,
      loader: 'style-loader!css-loader!less-loader'
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: "url-loader?limit=10000&mimetype=application/font-woff"
    }]
  }
};

module.exports = config;

webpack `stats.json` original filename?

Hey,

For my server side rendering, I would need to map the original filename/path to the generated one. To make require(xxxx.png) works in node.

Is there a way to achieve this easily?

0.5.8 is a breaking change, prolly should treat it as 0.6.0

v0.5.7
Do you want to request a feature or report a bug?
bug
What is the current behavior?
errors
If the current behavior is a bug, please provide the steps to reproduce.
have a project with node 0.10 and use url-loader. you will get an error

What is the expected behavior?
no error

Please mention other relevant information such as your webpack version, Node.js version and Operating System.

This post is mostly to make you aware that between v0.5.7 and v0.5.8 there is a breaking change where the loader-utils package switches from 0.2 to 1.0. That is a breaking change for anyone using a node version that does not understand const since const is a newer es6 keyword that does not exist in older versions of node. Our continuous delivery system failed on no changes on our part because we have ^0.5.7 in our package.json and the bump from 0.5.7 to 0.5.8 should have been considered a breaking change (for those of us with production systems using older node versions). Just an FYI.

Relative paths in url() are not resolved correctly for imported files with @import

When you @import a CSS file the relative paths are resolved based on the file I am importing into not relative to the imported file.

File structure

/assets/background.png
/assets/Layout.css
/component/Header/Header.css

Header.css

@import '../../assets/Layout.css';

Layout.css

body {
  background: url(background.png);
}

This throws an error, because for some reason after the import the relative path is no more relative to Layout.css. Any ideas?

Opt out of `limit`

To opt out you have to include a silly large value. If you want this and suggest a name for the option I'll implement it, what do you think @sokra. Thanks either way! (;

url-loader is encoding path instead of image

import tickImg from '../assets/tick.svg';
...
render () {
    return (
        ...
        <div style={{ backgroundImage: `url(${tickImg})` }} />
        ...
    );
}

Results in inline-style:

background-image: url("data:image/svg+xml;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJhc3NldHMvaW1hZ2VzL3RpY2stQ3lydkhSdi5zdmciOw==");

Decoding the base64 string:

module.exports = __webpack_public_path__ + "assets/images/tick-CyrvHRv.svg";

otf font not being loaded correctly

Here's my config:

{
      test: /\.(otf|eot|woff|woff2|ttf|svg|png|jpg)$/,
      loader: 'url-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!

Interoperate with `imagemin-webpack-plugin`

I'm the author/maintainer of imagemin-webpack-plugin. It's a plugin that does the same job as image-webpack-loader, but as a plugin so it can easily work on images that aren't require()d, but that are added from other plugins, loaders, or anything else.

I had an issue come in that images that were inlined from this loader weren't getting optimized, and after looking into it it's obvious that the problem is that this plugin doesn't add the image to the assets array, but instead just puts it right into the source asset.

That's not a problem in itself, but it means that my plugin doesn't ever see that image on the emit event so I can't touch it.

I guess I'm making this issue to see if anyone here knows of a good idea for how to solve this... I'll be the first to admit that I know very little about webpack internals (honestly I know just barely enough to make the plugin I made, and nothing more...), so I'm hoping there's something easy that i'm missing.

The issue in my repo for this is here, and I outlined a few of what I think are my options there.

Feel free to close this right away if it's the wrong place to ask or something. The pre-filled issue text was a bit confusing if this kind of thing is allowed here, so I apologise ahead of time if it's not.

SVG Stacking

I am trying to use SVG-Stacking in my project but seems that url-loader is not able to load it properly.

<img src="assets/icons/icons.svg#billing" />

screen shot 2016-11-10 at 10 51 05 pm

url-loader fails with error, when url src has query parameter in it.

@font-face {
   font-family: "Ionicons";
   src: url("./ionicons.woff2?v=3.0.0-alpha.3") format("woff2"),
}

The above one fails with the error as follows -

ERROR in ./ionicons.woff2?v=3.0.0-alpha.3
Module parse failed: /Users/sreek/test/app/ionicons.woff2?v=3.0.0-alpha.3 Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./ionicons.scss 6:85-120

where as, if I remove the version query parameter (?v=3.0.0-alpha.3) from the url src (as shown below), then it works just fine.

@font-face {
   font-family: "Ionicons";
   src: url("./ionicons.woff2") format("woff2"),
}

webpack.config.js

'use strict';
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var APP = __dirname + '/app';

module.exports = {
    context: APP,
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: __dirname + '/build'
    },
    module: {
        loaders: [
            {
                test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
                loader: 'url-loader?limit=1000&name=fonts/[name].[ext]'
            },
            {
                test: /\.(scss)$/,
                loader: ExtractTextPlugin.extract("css!postcss!sass"),
            },
        ]
    },
    plugins: [
        new ExtractTextPlugin("css/[name].css")
    ]
};

Is this an issue with url-loader? If not, any suggestions to get this working, when url src has query parameter appended to it?

Appreciate your time!

How do you actually include an image?

I get that you type require('image.png'), but how do you actually put that in your app?

I have tried <img src={require('image.png')} /> and just plain {require('image.png')}, but it doesn't work. I'm running out of idea.

Documentation URL

Do you want to request a feature or report a bug?

Bug?

What is the current behavior?
Documentation: Using loaders redirect you to old webpack website which is for v1, not for v2.

What is the expected behavior?
Redirect to new website which is for v2.

Load `.png` DataURI fails

var imgStr = require('url!./images/off.png');
open(imgStr);

and open a window showing an invalid image like this:
image

Is anything wrong with my code?

webpack-defaults upgrade

Addition of webpack-defaults & associated refactoring as a part of the next Major release

Issue exists for status tracking across the organization.

Please do not close

Image URL doesn’t resolve

This may very well be an issue with my setup outside of the url-loader… not sure.

Here is my url-loader config:

loaders: [
    {
        test: /\.(png|jpg|svg)$/,
        loader: 'url?limit=25000'
    }
]

In my component’s CSS file I have the following declaration:

.Base {
    background-color: rgb(83, 96, 108);
    background-image: url('./images/fonts-wallpaper_2x.png');
    background-size: 1760px 248px;
}

The url-loader does the proper thing and moves that image to my publicPath and updates the url for the image in the resulting CSS:

.CTA-001__Base-39mzM {
    background-color: rgb(83, 96, 108);
    background-image: url(/include/images/1eb425455da53643003af01f01e8231f.png);
    background-size: 1760px 248px;
}

Problem is the image never actually appears in the browser. When I right-click the image URL in the inspector and choose “Open link in new tab” it sends me to this URL:

chrome-devtools://devtools/include/images/1eb425455da53643003af01f01e8231f.png

If I actually type in the url http://my.local.site/include/images/1eb425455da53643003af01f01e8231f.png the image appears.

Any idea what the problem might be?

Double running loader

Hello! And thanks for this loader (and Webpack)! But I'm having a problem...
It seems to run twice when I do a require('url!../assets/imgs/file.png') from a JS file. So the second run is reencoding the encoded Buffer from the first run. In the end, I guess the string accessible in the Browser is not the encoded image, but the encoded module with the encoded image...
Am I doing anything wrong?

For now, I solved the problem adding something like this line in the loader:

if (content.toString().slice(0,16) == 'module.exports =') return content

Can the url-loader process base64 url?

The basic usage of url-loader is -

{
              test: /\.(png|jpg|svg)$/,
              exclude:/node_modules/,
              loader: 'url-loader?limit=100000',
              include: [
                path.resolve(__dirname, './src')
              ]
            }

But I'm trying to use Toastr. In their css file the background-image rule is like the following..

#toast-container > .toast-success {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==") !important;}

When I run webpack. The output is-

ERROR in ./~/toastr/build/toastr.css
Module parse failed: /Users/Admin/Downloads/kamal/development/client-app/node_modules/toastr/build/toastr.css Unexpected token (1:0)

Is it possible to process base64 url with url-loader?

Release a new version to npm

The dependency on mime was bumped a year ago, but there was never a new version released to npm containing it!

Browser support for data URI

According to the README,

The url loader works like the file loader, but can return a Data Url if it is supported by browser and the file is smaller than a limit.

However, from what I understand, the current implementation does not take browser support into consideration, nor does it have fallback in place. So which one is the real intention?

svg support

I took a stab at this, but failed due to my lack of webpack knowledge.

I thought it would be great to have the limit support the svg extension mimetype (image/svg+xml)

I found this on StackOverflow

Any thoughts?

limit parameter is not working correctly

Webpack logged the img size of 13kb, and I have the config:

loader: `url?limit=10000&name=img/[name]_[hash].[ext]` 

It outputs data-url instead of emitting file.

Using absolute path

I'm building a react application and using a very "deep" folder structure convention where each component has its own folder and sub components are nested withing those folders.
I also want to keep all my assets in one folder, is there a way to avoid require(../../../../logo.png) and somehow configure it to load images directly from my assets folder?

Is "prefix" query parameter supported?

Quoting the doc -

require("url?prefix=img/!./file.png");
// => Parameters for the file-loader are valid too
// They are passed to the file-loader if used.

Outside of this example, I haven't found any mention of the "prefix" parameter either in file-loader, or in loader-utils code. Is this parameter valid!?

Using ?v= in CSS url() doesn't work

To make

  src: url('../fonts/fontawesome-webfont.eot?v=4.1.0');

work, then ?v=4.1.0 must be removed.

What's the right way to handle this case?

prefix specific css file urls paths

set webpac.config to prefix url in background-image: url(prefix- path)
so if i have in css file something like:
.limage09o { background-image: url('/img/image.png'); }
i want webpack to add prefix to url('/img/image.png') like:
url('../../../../img/image.png')

require .png, .jpg, .gif works in chrome but not firefox

From @littlebee on November 24, 2015 23:9

I'm not sure what I've done, but I have this image:

notFoundUrl: require("../../img/petals.png")

That webpack seems to find and load just fine in Chrome but not in Firefox. My webpack loader config looks like:

      ,
        test: /\.(png|jpg)$/
        loader: 'url-loader?limit=8192' # inline base64 URLs for <=8k images, direct URLs for the rest

See for example: (http://zulily.github.io/react-datum/docs/examples/). The last two tiles on the left should have the petals.png image but show as broken, and render without a src on Firefox. I tested with two different machines with Firefox 42 and one hopelessly stuck on 36.

Thank you for your help.

Copied from original issue: webpack/webpack#1668

How to define a directory for bundled .woff

Hi there!

I'm using multiple woff fonts in my project. They are loaded with the url-loader, which (afaik) bundle all these files into a single one. This new woff file is located in config.output.publicPath.

Is there a way to change the target directory of these files? Like config.output.publicPath + fonts/
Thanks a lot!

edit:

Okay, it's just one wofffont (material icon font) which get transformed in a new woff file with an hash filename. Nevertheless I would love to define the directory for this new file.

Load images in JavaScript

I try to load images in JavaScript code and then use the base64 string as the src of images.

 const img1 = require("url?limit=10000!../../form/images/image1.png");
 const img2 = require("url?limit=10000!../../form/images/image2.png");

But when I decode the above base64 string I get something like the following:

module.exports = "data:image/png;base64,iVBORw0KGgoAA...

Why is the module.exports encoded as part of the image content?

require path

hi,sometimes i use require('./src/img/nobodyon.png') in js,i want to change the path into a variable,
like require(src) ,but it doesn't work

[Windows] generates wrong paths in css file

I use windows7, node: node-v4.4.5-x64, npm: 2.15.5, url-loader: 0.5.7, webpack:1.13.1

In the js file,I write like below:

require("layer-dialog/src/skin/layer.css");

webpack.config.js configurtion like below:

module:{
        loaders: [
          {test: /\.vue$/, loader: 'vue' },
          {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel'
          },
          {test: /\.css$/, loader: "style!css" },
          {test: /\.scss$/, loader: "style!css!sass"},
          {test: /\.less$/, loader: "style!css!less"},
          {
        test: /\.(png|jpg|gif|svg)$/,
                    loader: 'url',
                    query: {
                            limit: 1500,
                            name: 'imgs/[name].[ext]?[hash:7]'
                    }
          }
        ]
    },

but after complie, I open the js file,the image path generated is like below:

"imgs/node_modules\\\\layer-dialog\\\\src\\\\skin\\\\default\\\\icon.png?551539f"

the path is wrong. The correct path will be like below:

 "imgs/node_modules/layer-dialog/src/skin/default/icon.png?551539f"

about version upgrade

when you update "loader-utils" to "^1.0.2" from "0.2.x", you'd better update url-loader to "0.6.x" or "1.0.x".
because of loader-utils 1.x is used ES6 that's a big change but url-loader just change to 0.5.8 from 0.5.6.
it's lots of error when we use ~0.5.6

Add ability to set encodings

Hi @sokra!
Thanks for the great loader.

Default loader behaviour is to encode source and return Data URI. But for SVG is no necessary to encode source in base64, because it works with raw content encoded with encodeURIComponent. Moreover it will decrease ~30% of content length and save browser resources for unpacking base64 string. My suggestion is to add user defined handlers to specific mime-type, something like this:

{
  module: {
    loaders: [
      {
        test: /\.(jpg|png|gif|svg)$/
        loader: 'url?limit=10000'
      }
    ]
  },
  url: {
    handlers: {
      'image/svg+xml': function (content) {
        return 'data:image/svg+xml,' + encodeURIComponent(content);
      }
    }
  }
}

For backward compatibility option can be disabled by default. For details please take a look at my advanced-url-loader which based on url-loader. I can make a PR, if you agree. Also I want be a volunteer and cover all existing loader code with tests. And close some issues.

Can I extract all Base64 images string into one separated trunk?

My project has many small images, which are tansformed into Base64 string and increase the bundle size by 70~kb. Can I separate all the base64 images into one separated asynchronous trunk to get better performance, or I can just use sprite image? Thanks for your help!

[path] or [name] problem ?

Issue

I couldn't solve nested image folder when scss load url()

I've been always gotten assets/resources/assets/img/f/f2/example.png?eeeeeeeeee this kind of path;

if I only used [name], it will return:
assets/example.png?eeeeeeeeee

however I desire it will be assets/img/f/f2/example.png?eeeeeeeeee

  • nodejs v6.6.0
  • webpack 1.13.2
  • file-loader 0.8.5

Scss example

.example {
    background-image: url( "../img/f/f2/example.png" );

    // tried
    // background-image: url( "~img/f/f2/example.png" ); 
}

Folder structure

├── public
│   ├── assets
│   │   ├── css
│   │   ├── fonts
│   │   ├── img
│   │   └── js // Entry js file in this folder
├── resources
│   ├── assets
│   │   ├── img // images resource 
│   │   │   ├── a
│   │   │   ├── b
│   │   │   ├── c
│   │   │   ├── d
│   │   │   ├── e
│   │   │   ├── f
│   │   │   │   └── f2
│   │   │   ├── g
│   │   │   └── h
│   │   ├── js
│   │   └── scss
let config = {
    ...
    output: {
        path: path.resolve( __dirname, 'public/assets/' ),
        publicPath: '/assets/',
        filename: 'js/[name].js',
    },
    module: {
        loaders: [
            {
                test: /\.(jpe?g|png|gif|svg)(\?v=\d+\.\d+\.\d+)?$/i,
                loader: 'file-loader?name=[path][name].[ext]?[hash:10]',
                exclude: /(node_modules|bower_components)/
            },
            {
                test: /\.scss$/,
                // loader: ExtractTextPlugin.extract( 'css!resolve-url!sass' ), // tried
                // loader: ExtractTextPlugin.extract( 'css!postcssl!sass?sourceMap' ), // tried
                // loader: ExtractTextPlugin.extract( 'css?root=.!sass' ), // tried
                loader: ExtractTextPlugin.extract( 'css!sass' ) // tried
                exclude: /(node_modules|bower_components)/
            }
        ]
    },
    plugins: [
        // 打包css
        new ExtractTextPlugin( 'css/[name].css', {
            allChunks: true,
            // publicPath: '.' // tried
        } )
    ],
    resolve: {
            root: [
                // path.resolve( '..' ) //tried
            ],
            alias: {
                // 'img': path.resolve( './resources/assets/img' ) // tried
            },
            ...
        },

Note

I've referred many solutions to solve this problem, (whether using url-loader or file-loader)
however there aren't nested folders in image folder.
I could pass through 1 level folder easily, but that isn't in my case :(

How can I get correct path ?

I would appreciate if you can solve this problem.

strange error

I got a very strange error recently. I don't know whether or not it's url-loader's error. But I would be very pleased if you could figure out why this happen.
I ran into this trouble through image-webpack-loader, and I have commit a issue at that project. Here is the link

Here's my errors:
Module build failed: ModuleBuildError: Module build failed: Error: spawn /Users/Zero/projects/livebet-client-code/node_modules/pngquant-bin/vendor/pngquant EAGAIN
at exports._errnoException (util.js:949:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:182:32)
at onErrorNT (internal/child_process.js:348:16)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
at DependenciesBlock.onModuleBuildFailed (/Users/Zero/projects/livebet-client-code/node_modules/webpack-core/lib/NormalModuleMixin.js:315:19)
at nextLoader (/Users/Zero/projects/livebet-client-code/node_modules/webpack-core/lib/NormalModuleMixin.js:270:31)
at /Users/Zero/projects/livebet-client-code/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
at context.callback (/Users/Zero/projects/livebet-client-code/node_modules/webpack-core/lib/NormalModuleMixin.js:148:14)
at imagemin.buffer.then.catch.err (/Users/Zero/projects/livebet-client-code/node_modules/image-webpack-loader/index.js:42:9)
at process._tickCallback (internal/process/next_tick.js:103:7)

ERROR in ./feSRC/img/flags/[email protected]
Module build failed: Error: spawn /Users/Zero/projects/livebet-client-code/node_modules/pngquant-bin/vendor/pngquant EAGAIN
at exports._errnoException (util.js:949:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:182:32)
at onErrorNT (internal/child_process.js:348:16)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
@ .//css-loader?sourceMap&localIdentName=[path][name]---[local]---[hash:base64:5]!.//postcss-loader!./feSRC/view/pages/profile/index.scss 6:13630-13675

Extracting mp3 files

Mp3 files do not get extracted if I call:
require("url!./banana.mp3").
The same thing happens if I specify a rule inside webpack.config.js:
module: { loaders: [ { test: /\.mp3$/, loader: 'url' } ] }.

Both of these calls work if I use file-loader instead of url-loader.

How to build <img src="some.png" alt="some" />

I have three questions

First :

Like the title, I can't do anything to solve it.

Second :

background-image:url("../images/xxx.jpg");

was modified

background-image : url(images/xxx.jpg);

by url-loader

I don't know why .. and marks gone.

Last:

My webpack.config.js is :

test: /\.(png|jpg)$/,
loaders: ['url?limit=8192&digest=hex&size=16&name=image/[name].[ext]']

There is no image in image/ I don't know if image under limit so I don't know it cause by Second or this.

Thanks for your help!

Confused how this would ever work with a physical file (limit on)

Hi, thanks for this plugin. It works if I use it in combination with ExtractTextPlugin, where the urls get re-written on output.

However if it's using the normal blobs, then the paths in the blobs don't get re-written.

For example in a node_module I have a font-face decl. with src: url("../fonts/bla" and this is literally in the blob, but of course that's wrong and it needs to be based on where the assets have been copied to.

For example for loader: 'url-loader?name=assets/[name].[ext]', I would expect the url to be changed to be src: url("assets/fonts/bla", otherwise how would it find the file?

But also of course physical files don't get copied until I run this with ExtractTextPlugin, so I'm unsure how it would ever work in dev mode with a limit set?

Thanks for any pointers!

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.