How to NOT resolve paths with Webpack? - javascript

I'm working on a ReactJs project with Webpack and sass-loader, css-loader & url-loader.
I would like to not resolve the font-face paths and keep it exactly how it was set in the SASS file.
The issue:
If I call an absolute path (ie: http://fonts.com/my-font.eot or /path/to/my-font.eot), the path is not resolved.
However, if I use a relative path (ie: my-font.eot or path/to/my-font.eot), url-loader tries to resolve the path.
In my case, I need to use a relative path (even if it generates a 404 error).
What I tried:
I tried to exclude all font extensions in the url-loader, but Webpack doesn't know what to do with this type of file even if the file potentially doesn't exist.
Here the error I get:
Module parse failed: C:....\fonts\my-font.eot Unexpected character '
' (1:1) You may need an appropriate loader to handle this file type.
I also tried to disable the "url" option of css-loader, but absolutely nothing happens. I guess it is highly possible that I didn't add the option correctly:
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"],
options: { url: false }
},
Here is what my current code looks like :
module: {
loaders: [
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.scss$/,
/\.json$/,
/\.svg$/
],
loader: 'url',
query: {
limit: 10000,
name: 'path/dist/[name].[hash:8].[ext]'
}
},
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
},
...
]
},
...
}

This question might be a little old, but I still want to correct the answer.
When you want to use the array syntax, you basically define all the options for every single loader. In order to do so you have to use an object for the loader in the array. So instead of
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"],
options: { url: false }
},
You have to write
{
test: /\.scss$/,
loaders: [
"style-loader",
{
loader:'css-loader',
options: {
url: false
}
},
"sass-loader"],
},

I found the solution. I wasn't adding the css-loader option properly.
Because I didn't find a way to add options directly using the array syntax, I had to switch to the string syntax.
This code doesn't work:
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"],
options: { url: false }
},
This code works:
{
test: /\.scss$/,
loader: 'style!css?url=false!sass'
}

Related

Adding Flow type checking to Webpack, Babel & Eslint

I have a Webpack 4 config file that compiles ES6 React code to ES5 using Babel (plus stage 3 preset and some optimisation plugins). It lints the code with Eslint.
import path from 'path';
export default {
mode: 'development',
entry: './app/app.jsx',
devtool: 'inline-source-map',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
publicPath: '/dist/js',
},
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['es2015', 'stage-3', 'react'],
plugins: [
'babel-plugin-styled-components',
'transform-react-remove-prop-types',
'transform-react-inline-elements',
],
},
},
],
},
};
Now I want to add Flow type checking to my project but I can't find ANY good full examples of how a config setup like this should look.
I've tried adding eslint-plugin-flow to the Eslint config. I've tried adding babel-preset-flow to the Babel presets. I always end up getting errors either about needing an appropriate loader to handle the files, or it complains that my Flow code is invalid.
Note my config works before adding Flow. Can anyone show how to add Flow?

Webpack bundled JS not being executed

This is a very strange problem because actually, some of the bundled code is being executed. I use style loader for my CSS and that of course gets put into bundle.js and loads and works fine. However, I also have a file with some code to set up the jQuery localScroll plugin, and that code isn't working.
To test it, I included in the same file a call to console.log(), just telling it to write the number 4. If I open up bundle.js, I can see the console.log() call as well as the call to $.localScroll(), they just simply aren't running. Calling $.localScroll() manually from the console works as intended.
Here is the JS file in question:
console.log(4);
$(() => {
$.localScroll({duration: 800});
});
Here is my Webpack config:
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './webpack-entry.js',
plugins: [
new CleanWebpackPlugin(['dist']),
new webpack.optimize.UglifyJsPlugin()
],
output: {
filename: './javascripts/bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|jpeg)$/,
use: {
loader: 'url-loader',
options: {
limit: 8192,
fallback: 'file-loader',
name: './images/[hash].[ext]'
}
}
},
{
test: /\.pug$/,
use: [
{
loader: 'file-loader',
options: {
name(file) {
if(new RegExp(/partials/).test(file)) {
return './views/partials/[name].[ext]'
}
return './views/[name].[ext]'
}
}
},
'pug-asset-loader?root=./src'
],
},
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['env'],
}
},
]
}
],
}
};
Finally, here is bundle.js (my custom code seems to be at the very bottom, in some sort of array of functions). The non-uglified version is too long for SO, so here it is on Hastebin: https://hastebin.com/vululimupi.js
The problem is that you haven't defined this dependency as a module. Rewriting it following supported module format specs should help.
After some testing, it seems that the essential problem is just as #uKolka was saying - my files were not getting required as modules. While I'm still not entirely certain why their code was still appearing in my bundle file but not running, I have found a way to still reap the recursive benefits of require.context(). It seems that require.context() returns a function which is itself capable of resolving the files it logs in whatever folder you have pointed it at. It also has a member function keys() which quite conveniently returns each dependent file name and is easily used with forEach().
Given all that, this is how my webpack-entry.js looks now:
import './src/stylesheets/scss/master.scss';
require.context('./src/views', true, /\.pug$/);
const js = require.context('./src/javascripts/', false, /\.js$/);
js.keys().forEach(key => js(key));
This works just fine.
In my case it was due to Babel and React. If you use React, then try to call ./src/index.js directly and use "#babel/preset-env", "#babel/preset-react" in your .babelrc. You can take a look at my gist. and in your webpack.config.js:
{
test: /\.js?$/,
use: ["babel-loader"],
exclude: /node_modules/
},
take a look at the gist:
https://gist.github.com/Nagibaba/14e898d99a4be89b00a60d28abc19bc0
For ruby's rails/webpacker users only.
This question title and content made me find it before this issue which may be the correct answers for some users here. To avoid link rot, I'll explain it shortly below:
Make sure your #rails/webpacker npm library and webpacker gem both have the same exact version.
I ended up doing:
IO.foreach("package.json").find { |line| line[%r("#rails/webpacker": "(.*?)")]}
gem "webpacker", Regexp.last_match(1).tr("-", ".")

Webpack 3.5.5 error loading CSS and SASS

I am currently updating my nodejs packages and updated webpack to 3.5.5 and the build is now failing on trying to load css and sass. This is how my loaders look.
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader']},
{test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/, loader: "file-loader" },
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]-loader'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]-loader'},
{test: /(\.css|\.scss)$/, loaders: ['style-loader', 'css?sourceMap-loader', 'postcss-loader', 'sass?sourceMap-loader']},
]
I am wondering if I need to change anything so that these loaders will work?
The error I am getting is
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'css-loader' instead of 'css', see webpack.js.org/guides/migrating/… `
Now that webpack loaders must include the -loader prefix, the correct modification from css?sourceMap is not to css?sourceMap-loader but instead to css-loader?sourceMap.
Similarly, sass?sourceMap must become sass-loader?sourceMap.
In both cases, sourceMap acts in a similar way to a query string parameter in a URL, and the adjustment from css to css-loader is akin to a resource moving from example.com/css to example.com/css-loader.

Multiple package.jsons with ES6 Babel

I have a large project that I would like to divide up into multiple package.json's so that the dependencies for each part can be clearly stated and so those packages can be exported as individual parts.
However, I want my app to include each of these packages and compile them using webpack and babel. There are shared dependencies for the packages, so I don't want to just output each one to a /dist folder.
My ideal directory structure looks like this:
\main
\app
\node_modules
package.json
\package1
package.json
node_modules
index.js
\package2
package.json
node_modules
index.js
I tried multiple approaches:
Using webpack's resolve modules with something like path.resolve('app'). This just doesn't work, even though it should in theory.
Using main's package.json to reference others using "package1" : "file:../package1". This doesn't treat package1 as es6 javascript and throws errors. Using resolveLoaders in the webpack configuration does not help.
The webpack config I have is as follows.
module: {
loaders: [
{
test: /\.js?/,
loader: 'babel-loader',
include: [
path.resolve('app'),
path.resolve('../prose'),
],
query: {
plugins: [
['react-transform', {
transforms: [{
transform: 'react-transform-hmr',
// If you use React Native, pass 'react-native' instead:
imports: ['react'],
// This is important for Webpack HMR:
locals: ['module']
}]
}],
['transform-object-assign']
]
}
},
{ test: /\.css$/, loader: 'style-loader!css-loader!sass-loader' },
{ test: /\.svg$/, loader: 'file-loader' },
{ test: /\.png$/, loader: 'file-loader' },
{ test: /\.jpg$/, loader: 'file-loader' },
{ test: /\.json$/, loader: 'json-loader' }
]
},
resolve: {
modules: [
path.resolve('app'),
'node_modules',
],
extensions: ['.json', '.js', '.jsx'],
}
Any thoughts or examples of other projects that do this would be appreciated!
You should check out lerna. It enables you to use multiple package.jsons and even packages in one repo. It might help you with you requirements.

How to configure font file output directory from font-awesome-webpack in webpack?

I just installed font-awesome-webpack. I import it using: require("font-awesome-webpack");
My webpack config includes the following in my module loaders array:
{ 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" }
Problem is I am getting this error in developer console:
localhost/:1 GET http://localhost/mysite/app/db812d8a70a4e88e888744c1c9a27e89.woff2
localhost/:1 GET http://localhost/mysite/app/a35720c2fed2c7f043bc7e4ffb45e073.woff
localhost/:1 GET http://localhost/mysite/app/a3de2170e4e9df77161ea5d3f31b2668.ttf 404 (Not Found)
The problem is, those files are created at the root (within the mysite directory). How do I configure such that those woffs and ttf are output within the mysite/app directory?
I've recently wanted to use font awesome with webpack v1, I've installed the npm module font-awesome not font-awesome-webpack
You must install few loaders before :
npm i css-loader file-loader style-loader url-loader
and add use them in your webpack.config.js :
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css?sourceMap'
}, {
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}]
}
Now if you include in your entry.js :
require('font-awesome/css/font-awesome.css');
You normally be able to use font-awesome in your template :
<i class="fa fa-times"></i>
This gist helped me : https://gist.github.com/Turbo87/e8e941e68308d3b40ef6
As of Feb. 2016 this seems to be a common question with webpack, so I hope this provides some help. If you add this to the loader: '&name=./path/[hash].[ext]', that specifies where to look for those files. For example:
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff&name=./[hash].[ext]'
}
This places the correct URL to the fonts within the generated CSS file.
I recommend this method when dealing with anything other than css/scss. Hope this helps.
In addition to the above answers, I
I had to specify a path in output to get it working like so to specify the hosted location and not write the assets to the root path:
output: {
filename: "./bundle.js",
path: “./client”
},
module: {
loaders[
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff&name=./webpack-assets/[name]/[hash].[ext]"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff&name=./webpack-assets/[name]/[hash].[ext]"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream&name=./webpack-assets/[name]/[hash].[ext]"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file?&name=./webpack-assets/[name]/[hash].[ext]"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml&name=./webpack-assets/[name]/[hash].[ext]"
}
] // loaders
} // module
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=100000'
}
This schema helped me
This is my case, because of my script path is like below:
script(src='/javascripts/app.js')
So, I have to add '&name./javascripts/[hash].[ext]' to all font files like:
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff&name=./javascripts/[hash].[ext]"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff&name=./javascripts/[hash].[ext]"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream&name=./javascripts/[hash].[ext]"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file?name=./javascripts/[hash].[ext]"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml&name=./javascripts/[hash].[ext]"
}
Just as a note, I came across a similar fault using the font-awesome-loader.
Where the directory would not be set correct, regardless of any of the changes above.
To correct this, the option publicPath can be added to output:
output: { path: config.outputPath, filename: '[name].js', publicPath: '/assets/' },
The folder /assets/ will be changed to wherever you actually store your fonts.
Hopefully this helps.
I had font-awesome-webpack working on my PC, but it wouldn't work on my Mac. I think my PC was still throwing the 404s for the .woff2, .woff, and .tiff, but the icons displayed properly, so I ignored the problem.
My Mac, however, would not display the icons. While reading this Q&A, I tried a bunch of things. Here's what lead to my solution:
On my http://localhost:8080/View/ page, I was getting 404s that looked like the link below:
I entered http://localhost:8080/View/e6cf7c6ec7c2d6f670ae9d762604cb0b.woff2 into the browser, and confirmed the 404.
I tried going to http://localhost:8080/e6cf7c6ec7c2d6f670ae9d762604cb0b.woff2 (removing the extra path before the font file), and was able to access the file.
I modified Paul's answer to remove the . that made the file request relative.
For example, Paul suggested:
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff&name=./[hash].[ext]'
}
Take note of the &name parameter, that uses ./[hash].[ext]. I dropped the leading . and now there are no 404s (the browser correctly requests the files from the root of the site):
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff&name=/[hash].[ext]'
}
Conclusion: If your entry point is NOT at your web root, and you're able to access the font files at the web root, you probably just need to use this name configuration to fix the path.
Same issue faced.
Fixed it using the below syntax,
loader: "file?name=./fonts/[hash].[ext]"
fonts is the directory name, replace it with your own directory name.
Example:
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url?name=/build/[hash].[ext]&limit=8192&mimetype=application/font-woff"
}

Categories