webpack-contrib / url-loader Goto Github PK
View Code? Open in Web Editor NEWA loader for webpack which transforms files into base64 URIs
License: MIT License
A loader for webpack which transforms files into base64 URIs
License: MIT License
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.
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?
Perhaps we cann't require a variable? How to solve this problem?
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" />
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
.example {
background-image: url( "../img/f/f2/example.png" );
// tried
// background-image: url( "~img/f/f2/example.png" );
}
├── 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
},
...
},
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.
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
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?
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?
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
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 woff
font (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.
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.
i just want to use url-loader to limit imgs,then use file-loader to custome output folder,what should i do?thanks
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"
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.
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!
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! (;
When I use this plugin, it will be encode all of the file that less than the limit, but sometimes I don't want to encode though its file size less than the limit of my configuration
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.
IMHO it should be named data-uri-loader to avoid confusion
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)
Any thoughts?
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?
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.
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.
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?
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')
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.
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!?
The dependency on mime was bumped a year ago, but there was never a new version released to npm containing it!
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!
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!
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;
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?
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";
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.
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?
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
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
Just curious: why handle "minetype" here: https://github.com/webpack/url-loader/blob/master/index.js#L14 ? It seems unnecessary and may encourage bad spelling.
@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!
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
What the title says, I am not being able to do npm install due to this issue, the certificate expires on 9/6/2016
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!
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
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?
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.