Webpack: cannot resolve module 'file-loader' - sass

When I try to build SASS file with webpack, I got the following error:
Module not found: Error:Cannot resolve module 'file-loader'
note that this issue only happen when i try to load background image using relative path.
this Work fine:
background:url(http://localhost:8080/images/magnifier.png);
this cause the issue:
background:url(../images/magnifier.png);
and this is my project structure
images
styles
webpack.config.js
and this is my webpack file:
var path = require('path');
module.exports = {
entry: {
build: [
'./scripts/app.jsx',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server'
]
},
output: {
path: path.join(__dirname, 'public'),
publicPath: 'http://localhost:8080/',
filename: 'public/[name].js'
},
module: {
loaders: [
{test: /\.jsx?$/, loaders: ['react-hot', 'babel?stage=0'], exclude: /node_modules/},
{test: /\.scss$/, loaders: ['style', 'css', 'sass']},
{test: /\.(png|jpg)$/, loader: 'file-loader'},
{test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: 'file-loader'}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.scss', '.eot', '.ttf', '.svg', '.woff'],
modulesDirectories: ['node_modules', 'scripts', 'images', 'fonts']
}
};

As #silvenon said in his comment:
Do you have file-loader installed?
yes file-loader was installed but broken, and my issue has been solved by re-installing it.
npm install --save-dev file-loader

You may face a very similar issue if you are using url-loader with the limit configuration defined. As the documentation states, if the resource you are trying to load exceeds this limit, then file-loader will be used as fallback. Therefore, if you do not have file-loader installed, an error will prompt. To fix this error, set this limit to a bigger value or do not define it at all.
{
test: /\.(jpg|png|svg)$/,
use: {
loader: 'url-loader',
options: {
limit: 50000, // make sure this number is big enough to load your resource, or do not define it at all.
}
}
}

I has the exactly same issue and the following fixed it:
loader: require.resolve("file-loader") + "?name=../[path][name].[ext]"

Thanks for this - this was the final piece to get
Bootstrap, d3js, Jquery, base64 inline images and my own badly written JS to play with webpack.
To answer the question above and the solution to getting around the problematic
Module not found: Error: Cannot resolve module 'url'
When compiling bootstrap fonts was
{
test: /glyphicons-halflings-regular\.(woff2|woff|svg|ttf|eot)$/,
loader:require.resolve("url-loader") + "?name=../[path][name].[ext]"
}
Thanks!

If you are facing this issue while running jest, then add this in moduleNameMapper
"ace-builds": "<rootDir>/node_modules/ace-builds"

Error - ./node_modules/#fortawesome/fontawesome-free/css/all.min.cssdisabled.
Error: Module not found: Can't resolve 'url-loader'
Fixed by installing url-loader, ex:
run 'npm install url-loader --save-dev'

Related

Gatsby Develop Failing using gatsby-plugin-sass

After installing the gatsby-plugin-sass module:
When I try to run gatsby build, I get the following error:
ERROR
Unknown error from PostCSS plugin. Your current PostCSS version is 6.0.23, but autoprefixer uses 7.0.26. Perhaps this is the source of the error below.
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Browser queries must be an array or string. Got object.
File: src/indexs.sass
failed Building development bundle - 9.200s
I have been working on a resolution to this for hours. I have tried:
custom webpack rules in gatsby-node.js for sass files
reading, re-reading, and re-re-reading the instruction on gatsby's site
updating PostCSS using npm in every way I know how
So far, nothing has worked.
Why is it so complicated to get sass working with gatsby? When the documentation on gatsby's site makes it seem so easy?
Any suggestions what I can do to get this working?
in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}
In gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
},
},
`gatsby-plugin-sass`,
the sass import line in gatsby-browser.js:
import "./src/indexs.sass"
Using sass instead of node-sass saved my day.
remove node-sass
npm uninstall node-sass
or
yarn remove node-sass
and add sass aka dart-sass
npm install --save-dev sass
or
yarn add sass
then edit gatsby-config.js
plugins: [
{
resolve: `gatsby-plugin-sass`,
options: {
implementation: require("sass"),
},
},
]
now run gatsby develop
:)
I'm a bit late to the party but hopefully this might help someone.
I have Sass setup and working with Gatsby without to much extra config required.
Install both node-sass and gatsby-plugin-sass via npm.
npm install --save node-sass gatsby-plugin-sass
Include gatsby-plugin-sass in your gatsby-config.js file in plugins: [] as below with any other Gatsby plugins you maybe using.
module.exports = {
siteMetadata: {
title: `#`,
description: `#`,
author: `#`,
},
plugins: [
`gatsby-plugin-sass`,
],
}
Write your styles as .sass or .scss files and import your main styles.scss (or whatever you prefer to name it) either in your main Layout.js file or gatsby-browser.js file as below using the path to the location of your styles.scss file.
import "./src/styles/styles.scss"
I hope this works for you but if you have any other trouble add a comment and I'll try to reply back.
I hope someone chimes in on this to show how exactly to set up gatsbys sass plugin. I could not get it to work at all.
But I did find a workaround in my case:
I removed gatsby-plugin-sass from the plugins array in gatsby-config.js, turning it off (but I did not uninstall it using npm)
I installed postcss-node-sass and postcss
I added this info to the plugins array in gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`postcss-preset-env`)({ stage: 0 }),
require(`postcss-node-sass`)(),
],
},
},
I added a custom rule for webpack in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}

Webpack and SASS sourcemaps paths issue

I've make a very simple project to ilustrate the problem.
The project structure is:
The contents of webpack.config.js:
var path = require('path');
module.exports = {
entry: [
'./src/main.js',
'./src/main.scss'
],
output: {
path: path.join(__dirname, 'www/'),
filename: 'bundle.js'
},
module: {
loaders: [{
loaders: ['style-loader', 'css-loader?sourceMap', 'sass-loader?sourceMap'],
test: /\.scss$/
}]
},
devtool: 'source-map',
devServer: {
contentBase: 'www/'
}
};
The bundle generation is working properly, but when I debug the application, the SASS sourcemaps don't have the right base path:
Because it nests a second src/ folder in src/. I've tried to add to the sass-loader the sourceMapRoot option:
'sass-loader?sourceMap&sourceMapsRoot=src/'
But it doesn't fix the issue. I know it isn't significant, but I want to know if anyone have it working properly or have the same problem.
Best regards, thank you.

Error when combining sass-loader with css-modules

I'm getting the following error when using SASS's map-get.
ERROR in ./src/special.scss
Module build failed: ModuleBuildError: Module build failed: Unknown word (11:14)
9 |
10 | #mixin mediaquery($name) {
> 11 | #media #{map-get($breakpoints, $name)} {
| ^
12 | #content;
13 | }
14 | }
This is only happening when I use both the sass-loader and another loader.
I first thought this was caused by the PostCSS Loader, but it seems like it's the sass-loading causing problems and not transforming the scss when using css-modules.
I've created a sample repo illustrating the problem: https://github.com/tiemevanveen/sass-css-components-fail-example.
You can use the different branches to test:
master: CSS Modules + SASS
postcss CSS Modules + SASS + PostCSS
log-source: Uses CSS modules + SASS + Custom source logging module
no-css-modules: SASS + Custom source logging module
Only the first and the last branch run without errors.
I've created the log-source example to see what the sass-loader is returning and it looks like it's not transforming the sass (but this might also be me misinterpreting how the loaders work).
The other example without css modules does show the right transformed code..
I'm puzzled why the master branch (without postcss or another custom loader) is working fine though.. if something would be wrong with the sass-loader then that one should also fail right?
I've filed an issue, but I'm thinking this has more chance on StackOverflow since it's such a specific problem and might be more a config problem. Here's my webpack config:
const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
module.exports = {
devtool: 'source-source-map',
debug: true,
context: path.resolve(__dirname, './src'),
entry: {
app: './index.js'
},
output: {
path: path.resolve(__dirname, './static'),
filename: '[name].js',
publicPath: '/static/'
},
devServer: {
outputPath: path.resolve(__dirname, './static'),
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
new WriteFilePlugin()
],
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', [
'css?modules&importLoaders=1&localIdentName=[path]_[name]_[local]',
// 'postcss-loader',
'sass'
])
},
// + js loader
]
},
postcss: [
autoprefixer({ browsers: ['> 0.5%'] })
],
resolveLoader: {
fallback: [
path.resolve(__dirname, 'loaders'),
path.join(process.cwd(), 'node_modules')
]
},
resolve: {
extensions: ['', '.js', '.json'],
}
};
You need to increase the importLoaders query parameter as you add loaders. That feature is poorly documented and confusing, but in your samples repo, importLoaders=2 with both Sass and PostCSS works.

Using Slick-Carousel and NPM

Still trying to master NPM and hit some roadblocks.
My slick-carousel works great when I use the CDN process. But I'm doing everything in NPM so figured I should do the same with this plug-in, but can't seem to get it off the ground.
Ran the install:
npm install slick-carousel --save
Which adds to my package.json file:
"devDependencies": {
"copy-webpack-plugin": "^3.0.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"gh-pages": "^0.11.0",
"html-webpack-plugin": "^2.21.0",
"img-loader": "^1.3.1",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^1.13.1"
},
"dependencies": {
"font-awesome-webpack": "0.0.4",
"jquery": "^3.0.0",
"slick-carousel": "^1.6.0"
}
I'm smart enough to know that I need to require the file in my index.js file:
var $ = require('jquery');
require("../css/style.css");
require("font-awesome-webpack");
require("slick-carousel");
I can see that I now have all the jQuery for slick-carousel, but none of the css.
Now I figure I should require the two .css files living in the node_modules folder:
require("slick-carousel/slick/slick.css");
require("slick-carousel/slick/slick-theme.css");
And this is where it all breaks. The slick.css file loads and the basic slick-carousel is now working in my html output. But the slick-theme file breaks everything by pushing this error:
./~/slick-carousel/slick/ajax-loader.gif
Module parse failed: /Users/ryanbuchholtz/Documents/thinkful/haventower/node_modules/slick-carousel/slick/ajax-loader.gif Unexpected character '' (1:7)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:7)
This makes me think something is broken in my webpack.config.js:
var path = require('path');
var packageData = require('./package.json');
var filename = [packageData.name, packageData.version, 'js'];
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CopyWebpackPlugin = require('copy-webpack-plugin');
var plugins = [
new HtmlWebpackPlugin({
inject: 'head',
template: 'index.html',
minify: {
"collapseWhitespace": true,
"removeComments": true,
"removeRedundantAttributes": true,
"removeScriptTypeAttributes": true,
"removeStyleLinkTypeAttributes": true
}
}),
new ExtractTextPlugin('style.css')
];
module.exports = {
entry: {
main: [
path.resolve(__dirname, packageData.main)
]
},
output: {
path: path.resolve(__dirname, 'build'),
filename: filename.join('.'),
},
devtool: 'source-map',
plugins: plugins,
module: {
loaders: [
{
test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader", "file-loader")
},
{ test: /\.(jpe?g|png|gif|svg)$/, loader: "file-loader"
},
{ 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"
}
]
}
};
I could really use some assistance in the best way to use slick-carousel while building in NPM and with webpack. So many moving pieces and, when I kinda think I get it, this comes along and I spend 7 hours trying to fix it before asking for help.
Any help is deeply appreciated.
I had the same issue, but I didn't want to change slick-carousel in my project, so one month late but here is how I solved it:
First install Webpack image-loader:
$ npm install image-webpack-loader --save-dev
Then change these lines (in your webpack configuration):
loaders: [{
test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader", "file-loader")
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{ 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"
}]
This will change file-loader (what you are using for loading images) for image-loader, it will know how to compile .gif files and other formats.
For aditional information about this, you can check the github page
Also, if you are using ReactJS, don't use slick-carousel directly, because it uses direct DOM manipulation thanks to JQuery dependency, right now I'm using react-slick is very stable and has cool options like settings based on responsive layout custom prev and next arrows and more.
I hope it help you
require("slick-carousel/slick/slick.css");
require("slick-carousel/slick/slick-theme.css");
From what I understand you do not need both of these - only one.
Slick-theme is the default CSS, while Slick you integrate.
I could be wrong (I'm really new to development) but I've had no problems with the initial configuration!

Webpack SASS-loader include statement breaks SASS #import statemetns

So for background originally I was excluding the node_modules directory in my Webpack config, which was working fine for my sass #import statements, but made it very difficult to include things from the node_modules directory. So I switched the SASS loader to the following
{
test: /\.scss$/,
include: [path.resolve(__dirname, "/src/client"), path.resolve(__dirname, "/node_modules/angular-material/")],
loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
},
Please also note I tried with and without the trailing slash on client.
All my src files including the sass files are in ./src/client directory including sub-directories. The problem now is when I run Webpack all my import statements are no longer functional. and I end up with the following error whenever I try to import one of my own sass files:
ERROR in ./src/client/app/app.scss
Module parse failed: /Users/mikedklein/development/vncuxf/src/client/app/app.scss Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
| #import 'common/common';
| #import 'general';
|
# ./src/client/app/app.module.es6 85:0-21
If I comment out the include statement all is well, but I know this is not a good approach. For reference I have also included my resolve statement from my config:
// Resolves so require statements don't need extentions
resolve: {
extensions: ['', '.js', '.es6', '.scss', '.css', '.html', '.json'],
alias: {
angular_material_scss: __dirname + "/node_modules/angular-material/angular-material.scss"
}
}
So I think I solved this
module: {
loaders: [
{
test: /\.(es6|js)$/,
exclude: /node_module/,
loader: 'babel-loader'
},
{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader!autoprefixer-loader'
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!autoprefixer-loader!sass loader'
}
]
},
// This is the key need to have include paths in the sass loader option.
sassLoader: {
includePaths: [path.resolve(__dirname, './src/app'), path.resolve(__dirname, '/node_modules/angular-material')]
}
One thing I am still curious about is whether this is the most efficient approach, when sass files are stored in multiple directories.

Resources