I have issue compiling my SASS code.
I would like to use a background image, but when I tried this, all my css stopped working.
My SASS file looks like this
#import "~bootstrap/scss/bootstrap";
#import "constants";
#crossroad {
position:relative;
background-image: url("../assets/bg.jpg");
}
My Webpack.config
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: "development",
module: {
rules: [
{
test: /\.(scss|png|jpg)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('autoprefixer')
];
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'resolve-url-loader'
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
}
]
}
};
ERROR MESSAGE:
ERROR in ./src/assets/bg.jpg (./node_modules/css-loader/dist/cjs.js!./node_modules /postcss-loader/src??ref--4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/assets/bg.jpg)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Invalid CSS after "����": expected "{", was ""
on line 1 of /Users/adrianmindek/Code/PersonalPage/src/assets/bg.jpg
����
^
# ./src/assets/bg.jpg 2:26-236
# ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src??ref-- 4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/scss/app.scss
# ./src/scss/app.scss
# ./src/app.js
I tried to add resolve-url-loader to my webpack config, but nothing changed.
You should handle file using file-loader like this
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
You can view code from here
Related
When I try to use command npm start, I get error
"] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema."
Code: https://next.plnkr.co/edit/hEHTiPYQXQ7POWIH?open=lib%2Fscript.js&deferRun=1
Here is my full configuration code for webpack
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app/app.js',
output: {
path: './dist',
filename: 'app.bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Error:
Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
[0] ** browser-sync config **
[0] { injectChanges: false,
[0] files: [ './**/*.{html,htm,css,js}' ],
[0] watchOptions: { ignored: 'node_modules' },
[0] server: { baseDir: './', middleware: [ [Function], [Function] ] } }
] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
[1] - configuration.module has an unknown property 'loaders'. These properties are valid:
[1] object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
[1] -> Options affecting the normal modules (`NormalModuleFactory`).
[1] - configuration.output.path: The provided value "./dist" is not an absolute path!
[1] -> The output directory as **absolute path** (required).
I found your problem webpack use rules config not loader config so change your code into this
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require("path");
module.exports = {
entry: 'src/app/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Update: move your index.html file into same level of webpack.config.js
I dont see in the document they allow user to change into different path
Please let me know if you still have a problem
I've been on a dependencies upgrade mission and I have found when upgrading Webpack to 4.24.0 or above I get this failure:
ERROR in ./src/js/components/App.jsx 35:9
Module parse failed: Unexpected token (35:9)
You may need an appropriate loader to handle this file type.
| import ReactModal from 'react-modal';
| var RoomListings = React.lazy(function () {
> return import('./RoomListings.jsx');
| });
| var RoomDetails = React.lazy(function () {
# ./src/js/index.js 3:0-39 6:74-77
# multi ./src/js/index.js
It's failing on the import but what is frustrating is that nothing has changed in either my Webpack or Babel config which are below:
webpack.config.js
module.exports = {
entry: ["./src/js/index.js"],
output: {
path: PATHS.build,
filename: "js/[name].js"
},
devServer: {
contentBase: path.join(__dirname, 'src'),
publicPath: '/'
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.html$/, loader: "html-loader" },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.(png|jp(e*)g|svg)$/, use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
.babelrc
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["add-react-displayname", "#babel/plugin-syntax-dynamic-import", "emotion"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
I am assuming something is either missing or misconfigured, but after hours of searching SO and Google, none of the existing answer appear to help.
I want extract and compile css code from sass file with extract-text-webpack-plugin , but webpack give me this Error :
ERROR in ./style.scss
Module parse failed: H:\projects\new\app\style.scss Unexpected token (1:4)
You may need an appropriate loader to handle this file type.
| body{
| background-color: #d9534f;
| }
# ./index.js 2:0-22
my version of webpack and extract-text-webpack-plugin :
"extract-text-webpack-plugin": "^2.0.0-beta.4",
"webpack": "^2.1.0-beta.22"
my webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let extractCSS = new ExtractTextPlugin('test.css');
module.exports = {
context:path.resolve(__dirname, 'app'),
entry: './index.js',
output: {
path: path.resolve(__dirname, 'app'),
filename: 'bundle.js'
},
module: {
loader: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
, {
test: /\.s?css$/,
loader: extractCSS.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' })
}
, {
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.(jpe?g|png|gif)$/,
exclude: /(node_modules)/,
loader: 'url-loader?limit=10000'
},
{
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: 'url-loader'
}
]
},
plugins: [
extractCSS,
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'app')+'/index.html',
inject: 'body'
})
]
};
and my simple .scss file :
body{
background-color: #d9534f;
}
Works for me this way.
Add const ExtractTextPlugin = require("extract-text-webpack-plugin"); in the top.
and add this to loaders:
test: /\.s?css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader!sass-loader'}),
},
I Solve it :
module: {
loaders: [
{
instead of
module: {
loader: [
{
here you go buddy
{ test: /\.sass$/, use: extractText.extract({ fallback: 'style-loader', use: 'css-loader!sass-loader' }) }
I'm requiring a bunch of .css files from my npm modules in my main.js file which is the entry point of my webpack config, as you can see here:
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
module.exports = {
entry: {
dashboard: './js/main.js',
vendor: ["fixed-data-table","react","react-dom","jquery", "bootstrap"],
},
output: { path: "../resources/public", filename: 'bundle.js' },
plugins: [
new webpack.optimize.CommonsChunkPlugin({name: "vendor", filename: "static/vendor.bundle.js"}),
new ExtractTextPlugin("[name].css"),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
],
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', 'stage-0']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader'}),
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader',
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
};
If I do not test for fonts and images, i will get errors building since some modules, for example bootstrap.css, will look for .png and various fonts.
So I added the loaders for testing images and fonts, which now works: It will build!
However, it also processes and outputs a bunch of .png, .woff2, .eot, .tff files to the same output folder which I don't want.
A "dirty fix" would be to make a .sh script where I just delete these specific files after running webpack in the terminal. But I'd rather not do that.
How can I change my webpack config to test for images and fonts, but not process and output them to the output folder?
The "dirty" solution is simply to output those files to the trash as such:
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=~/.local/share/Trash/[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=~/.local/share/Trash/[name].[ext]'
}
It works but it surely shouldn't be done this way :)
{ test: /\.jpg$/, loader: "file-loader?name=assets/images/[hash].[name].[ext]"},
{ test: /\.png$/, loader: "file-loader?name=assets/images/[hash].[name].[ext]&mimetype=image/png"},
{
test: /\.(html|hbs)$/,
loaders: ['handlebars-template-loader']
},
// Bootstrap 4
// { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery' },
// Bootstrap 3
// { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?name=assets/fonts/[hash].[name].[ext]&limit=10000',
},
{ test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=assets/fonts/[name].[ext]' },
{
test: /\.(eot|svg)(\?[\s\S]+)?$/,
loader: 'file?name=assets/fonts/[hash].[name].[ext]',
}
Somewhere in the middle of my Angular template I have img tag:
<img src="../../images/error.gif" />
Until now I was using raw-loader with this simple configuration:
test: /\.html/,
loader: 'raw'
But after i read this i decide I need a change:
The raw-loader is supposed to turn a text file into a CommonJS module
that exports the file contents as a string – nothing more.
What did I change:
So I changed my raw-loader to html-loader based on this article and this question.
{
test: /\.html$/,
loader: [
"html?" + JSON.stringify({
attrs: ["img:src", "img:ng-src"]
})
]
}
And this: loader
{ test: /.gif$/, loader: "file" }
Based on this and this questions I added publicPath: "/assets" to my webpackconfig.
And changed img tag on <img src=" { require('/assets/logo.png') } " />
My webpackconfig looks like:
webpack({
entry: path.resolve(__dirname, './main.js'),
output: {
path: dir_dist,
filename: 'custom-shared-lib.js',
publicPath: "/assets"
},
module: {
preLoaders: [
{
test: dir_bin,
loader: path.resolve(__dirname, "./my-loader.js"),
query: JSON.stringify(preLoaderQuery)
},
],
loaders: loader
},
plugins: [
// Avoid publishing files when compilation fails
new webpack.NoErrorsPlugin()
],
}, function(err, stats) {
console.log(stats.toString());
});
While variabile loaders are:
[
{
test: /\.js$/,
include: [dir_bin, dir_src],
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.html$/,
loader: [
"html?" + JSON.stringify({
attrs: ["img:src", "img:ng-src"]
})
]
},
{ test: /.gif$/, loader: "file" }
]
Error:
This error happen while compiling:
Module not found: Error: Cannot resolve 'file' or 'directory' ./ {
require('/assets/error.gif') }
I would be happy for any advice.