问题
I am trying to compile my Sass via webpack. Compiling normal sass is fine but I get an error.
Module not found: Error: Can't resolve '../img/twitter.svg' in '/Users/Steve/mywebsite/scss'
@ ./~/css-loader!./~/sass-loader/lib/loader.js!./scss/main.scss 6:94501-94530
Is there a way to resolve this? Alternatively is there a way to set the level of the sass compiler to be less strict to just ignore certain errors
Below is my current config.
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
resolve: {
alias: {
'masonry': 'masonry-layout',
'isotope': 'isotope-layout'
}
},
entry: './main.js',
output: {
path: path.resolve(__dirname, './dist/dist2'),
filename: 'bundle.js'
},
module: {
rules: [
{
test : /\.(png|jpg|svg)$/,
include : path.join(__dirname, '/dist/img'),
loader : 'url-loader?limit=30000&name=images/[name].[ext]'
},
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader'],
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
]
},
plugins: [
//new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('ross.css')
]
};
回答1:
You have not specified any loaders for images in your webpack file.
- Install
url-loader
andfile-loader
to your package.json
via
npm install --save url-loader file-loader
Inside your webpack config file add following -
{ test : /\.(png|jpg|svg)$/, include : path.join(__dirname, 'img'), loader : 'url-loader?limit=30000&name=images/[name].[ext]' }, // inline base64 URLs for <=30k images, direct URLs for the rest
回答2:
I didn't have any luck with url-loader
and file-loader
as suggested in the other answer. I was able to solve it using resolve-url-loader
module: {
rules: [
{ // sass / scss loader for webpack
test: /\.(sass|scss|svg|png|jpe?g)$/, //Make sure to allow all necessary file types here
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
importLoaders: 1,
minimize: true,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: "resolve-url-loader", //resolve-url-loader needs to come *BEFORE* sass-loader
options: {
sourceMap: true
}
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
})
}
],
},
回答3:
I know this is late, but for anyone looking for a workaround this error;
In my case the image was loading perfectly in the template, however, Webpack was returning an error: Module not found: Error: Can't resolve './path/to/assets.png'
Fix/Workaround:
Add ?url=false
to your css-loader, that will disable url handling by the css-loader :
...
{
loader: "css-loader?url=false"
},
...
来源:https://stackoverflow.com/questions/42575712/webpack-sass-cannot-resolve-images