webpack-contrib / file-loader Goto Github PK
View Code? Open in Web Editor NEWFile Loader
License: MIT License
File Loader
License: MIT License
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!
Problem: When Webpack is running in watch mode with a cache object, static files are always emitted, regardless of whether the source file has changed.
Expected: If the source file hasn't changed, don't emit the asset.
Would fix #55
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"
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.
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.
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
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.
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!
Is there anyway I can skip the files being rebuild every time the build runs? I don't see why I would want that in files that haven't change. Am I missing something?
Thanks 👍
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/
The newly added dependency won't build on a windows machine unless you have openssl installed in a specific location (C:/OpenSSL-Win64 or C:/OpenSSL-Win32 or 32-bit machine).
The generated exports
line has no trailing semicolon, which yields jshint warnings.
235:84: Missing semicolon. (code W033)
>> module.exports = __webpack_require__.p + "fa40c1f01e7a257d9ec200925f173201.eot"
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:
I have actually solved any public path issues during webpack-dev-server by setting
output.publicPath = '/'
when running the webpack-dev-serveroutput.publicPath = ''
when running webpackThe 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.
options.context
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 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.
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 ?
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!
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]
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:
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.
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!
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!)
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.
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.
sample.js
require.ensure([], function(require) { require("./app"); });
config
loaders: [{ test: /\.js[x]?$/i, loader: "file?name=js/[hash].js!babel", exclude: /node_modules/ },
Now this ends up skipping the parsing of the ./app
which, in this scenario will be the main file, and outputs the bundle with sample.js file as is
.
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
When using a output.publicPath
containing the compilation hash, I'm getting the wrong path added to CSS files that have paths replaced.
see webpack/webpack#446 for details
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.
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.
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?
Hi,
I am trying to match and use it on the loader: E.g.:
{
test: /(.*)\/assets\/img\/(.*)\.(svg|png|gif|jpg|jpg)$/,
loader: 'file?name=/assets/[0]/img/[name].[ext]'
},
Looking at: https://github.com/webpack/file-loader/blob/master/test/correct-filename.test.js
I can't find an example of:
"[N] the N-th match obtained from matching the current file name against the query param regExp"
Is this possible?
cheers
Leonardo
Smth like:
loader: "file-loader?name=[chunkname]_[name].[ext]"
Or is there a workaround to achieve that?
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.
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
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;
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
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!
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 :))
but for some reason I can't get the require('./file.mp4')
to work.
I posted a question on StackOverflow about this. Any ideas why this isn't working?
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:
{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 brokeconst 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 sourcesIn 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.
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.
path = require 'themes/' + themeCode + '/locale/' + languageCode + '.json'
/src/themes/civic/locale/en.json
{test: /\.json$/, loader: "file-loader"}
/build/03f272c55f8da7ff3616a17654816467.json
{test: /\.json$/, loader: "file-loader?name=[path][name].[ext]"}
/build/src/themes/civic/locale/en.json
/build/locales/civic/en.json
{test: /\.json$/, loader: "file-loader?name=locales/[context[0]]/[context[1]].[ext]"}
Thanks for any feedback
the prefix params is not support ?
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.
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
Example:
entry: ./shares/templates/app.html
{
test: /.(html|xml)$/,
loader: 'file?name=templates/[1]/[2]®Exp=([^/]+)[/\]templates/\$'
}
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
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.
Is it possible to stop WebPack from emitting files loaded by file-loader that are also entry points?
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'
]
}
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
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.