Images not loading Webpack/Webpack-dev-serve - javascript

all my images seem to be 404, I think I have the right path as I just stuck them in the root directory
I am using file loader and trying to load svg files
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require('webpack');
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
// filename and path are required
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
// JSX and JS are all .js
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./src/index.html"
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
]
};
here is an example I setup: https://github.com/chobo2/webpack-serve-example

You have to import:
import image from './Freesample.svg'
And use it like;
<img src={image}/>
But you also need an appropriate loader for it, another rule:
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
// filename and path are required
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
// JSX and JS are all .js
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
{
test: /\.(png|jpg|jpeg|gif)$/,
loader: 'file-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./src/index.html"
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
]
};

You need to use import.
import image from './Freesample.svg'
And use it like;
<img src={image}/>

Related

Issue with integrating cortex-js/compute machine in react application

I am trying to use compute machine provided by the cortexjs. https://cortexjs.io/compute-engine
I saved this dependency using
npm i #cortex-js/compute-engine
After I ran npm start, I am getting this error:
ERROR in ./node_modules/#cortex-js/compute-engine/dist/compute-engine.min.js 2:1360
Module parse failed: Unexpected token (2:1360)
You may need an appropriate loader to handle this file type.
Following is my webpack file:
var webpack = require('webpack');
const HtmlWebPackPlugin = require("html-webpack-plugin");
var path = require('path');
module.exports = {
// output: {
// path: path.resolve(__dirname, 'dist'),
// filename: 'main.js',
// publicPath: '/'
// },
mode : 'production',
devServer: {
historyApiFallback: true,
},
devtool: "source-map",
module: {
rules: [
{
test: /\.(png|jpg|woff|woff2|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
options: {
import: true,
},
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
Please can someone suggest which loader should I add to webpack.config file to make this work.

Cannot load image webpack (4.41.0)

I am trying to load a jpg image file using Webpack, but I keep getting the following error: Uncaught Error: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleParseError: Module parse failed: Unexpected character '�' (1:0)
I'm using file-loader, so I'm not sure what's wrong...
This is my webpack.config.js file:
module.exports = {
context: __dirname,
entry: {
frontend: ['./src/index.js', './src/sass/style.scss'],
customizer: './src/customizer.js'
},
output: {
path: path.resolve(__dirname, 'public'),
filename: '[name]-bundle.js'
},
mode: 'development',
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.(jpe?g|JPG|png|gif)\$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: 'public/images',
name: '[name].[ext]'
}
}
]
}
My image is currently stored in a src/images directory. What could I be missing?
Thanks for your help!
Edit: Here is the CSS I'm using to pull in the image:
#header {
background: url('../images/header.JPG') no-repeat center center fixed;
background-size: cover;
}
Edit: Here is my entire webpack.config.js file:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
module.exports = {
context: __dirname,
entry: {
frontend: ['./src/index.js', './src/sass/style.scss'],
customizer: './src/customizer.js'
},
output: {
path: path.resolve(__dirname, 'public'),
filename: '[name]-bundle.js'
},
mode: 'development',
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
enforce: 'pre',
exclude: /node_modules/,
test: /\.jsx$/,
loader: 'eslint-loader'
},
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.s?css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
},
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
options: {
extract: true,
spriteFilename: 'svg-defs.svg'
}
},
{
test: /\.(jpe?g|JPG|png|gif)\$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: 'public/images',
name: '[name].[ext]'
}
}
]
}
]
},
plugins: [
new StyleLintPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css'
}),
new BrowserSyncPlugin({
files: '**/*.php',
proxy: 'http://mysite.test/'
})
],
optimization: {
minimizer: [new UglifyJsPlugin(), new OptimizeCssAssetsPlugin()]
}
};```
test: /\.(JPG|gif|svg|gif|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
include: SRC,
use: [{
loader: 'file-loader'
}]
.
.
.
First try to replace your sass regex test like this :
test: /\.(sass|scss)$/
if it didn't work try replacing your whole rule like this :
{
test: /\.(sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
}
]
}
also remove {filename: '[name].css'} from MiniCssExtractPlugin
with the two tries I mentioned keep it simple like that :
plugins:[
...
new MiniCssExtractPlugin(),
...

Webpack - Sass loader not compiling Sass

I'm trying to introduce Sass-loader to an existing project so as to be able to use Sass in my React components. I've set this up successfully before in my own boiler plates and had no issues but for some reason with the current configuration it doesn't seem to play. It doesn't give any errors but rather doesn't do anything with my .scss file i'm trying to import.
I can see that there is some loaders in the cssLoaders config for Webpack which could be the culprit but I am only targeting .scss/ .sass files with the rule
test: /\.s(a|c)ss$/
so I wouldn't have thought this would affect it at all.
I have webpack setup with a common file and one for development. Here are both those files:
webpack.common.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
require('babel-polyfill');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: {
main: ['babel-polyfill', './src/index.js']
},
output: {
filename: '[name].[hash].js',
path: path.resolve('./dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: ['node_modules'],
use: [{ loader: 'babel-loader' }]
},
{
test: /\.s(a|c)ss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
outputPath: 'images/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|otf)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
}
]
},
plugins: [
new ErrorOverlayPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebPackPlugin({
template: 'index.html'
}),
new Dotenv(),
new CleanWebpackPlugin(['dist'])
]
};
And here is webpack.dev.js
const path = require('path');
const webpack = require('webpack');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const paths = require('../paths');
module.exports = require('./webpack.config.base')({
bail: false,
devtool: 'cheap-module-eval-source-map',
stats: 'errors-only',
performance: {
hints: false
},
entry: {
main: [
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appPolyfillsJs,
require.resolve('react-error-overlay'),
paths.appIndexJs
]
},
output: {
pathinfo: true,
filename: 'static/js/[name].js',
chunkFilename: 'static/js/[name].chunk.js',
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath)
},
// Load the CSS in a style tag in development
cssLoaders: [
{
loader: require.resolve('style-loader'),
options: {
sourceMap: true
}
},
{
loader: require.resolve('css-loader'),
options: {
modules: false,
sourceMap: true,
importLoaders: 1
}
},
{
loader: require.resolve('postcss-loader'),
options: { sourceMap: true }
}
],
babelQuery: {
cacheDirectory: true
},
plugins: [].concat([
new ProgressBarPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: true
})
])
});
The part that I have added to the configuration is in webpack.common:
{
test: /\.s(a|c)ss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
I then just import it in the module like so:
import React, { PureComponent } from 'react';
import './test.scss';
...
Can anyone spot why the configuration is wrong?
The sass-loader requires node-sass and webpack as peerDependency.
Make sure node-sass is installed and edit the loader webpack.dev.js like so:
{
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}

webpack does not output css

Situation
I have a webpack setup, where I have a rule that extracts CSS and/or SASS from .ts files using the extract-text-webpack-plugin and sass-loader.
I import my SCSS file in a seperate .ts file
import './scss/style.scss'
Problem
A CSS file is expected to be in the output folder ( dist ).
The compilation completes without an error, yet there is no CSS file in the build folder.
Here is my webpack configuration:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var styleString = require('css-to-string-loader');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: "[name].css",
disable: process.env.NODE_ENV === "development"
});
var helpers = require('./helpers');
var isProd = process.env.NODE_ENV === 'production';
module.exports = {
entry: {
polyfills: './src/polyfills.ts',
vendor: './src/vendor.ts',
app: isProd ? './src/main.aot.ts' : './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [{
test: /\.ts$/,
loaders: [
'babel-loader',
{
loader: 'awesome-typescript-loader',
options: {
configFileName: isProd ?
helpers.root('tsconfig-aot.json') :
helpers.root('tsconfig.json')
}
},
'angular2-template-loader'
],
exclude: [/node_modules/]
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[ext]'
},
{
test: /\.(json)$/,
loader: 'file-loader?name=assets/mocks/[name].[ext]'
},
{
test: /\.(css|scss)$/,
loaders: ['to-string-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
Reason
The reason there is not output CSS file is because you are not using the
const extractSass = new ExtractTextPlugin({
filename: "[name].css",
disable: process.env.NODE_ENV === "development"
});
in your CSS|SCSS rule
{
test: /\.(css|scss)$/,
loaders: ['to-string-loader', 'css-loader', 'sass-loader']
}
Solution
You have to make use of the use property like so:
{
test: /\.(css|scss)$/,
use: extractSass.extract({ // <==== Right here, note the "extractSass"
use: [
{ loader: "to-string-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
],
fallback: "style-loader"
})
}
And add to your plugins array the ExtractTextPlugin instance ( extractSass ):
plugins: [
extractSass
]
You might also want to take a look here.

Webpack doesn't generate app.bundle.css

I have the following webpack file, however, when I run npm run dev the name.bundle.css file doesn't get generated: (no errors either)
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './resources/'),
entry: {
app: './index.jsx'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './public/assets/'),
publicPath: '/assets/'
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader'
}],
}),
},
{
test: /\.jsx|js$/,
exclude: [/node-modules/],
use: [
{
loader: "babel-loader",
options: { presets: ['react', 'es2015', 'stage-1'] }
}
]
},
{
test: /\.(sass|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]']
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=public/fonts/[name].[ext]'
}
]
},
resolve: {
modules: [
path.resolve(__dirname, './resources/'),
'node_modules'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css'
})
]
}
my CSS folder is:
CSS
- app.scss
COMPONENTS
comp1.scss
comp2.scss
it works this way "import styles from './css/app.scss';" but I would expect this to generate a app.bundle.css:
new ExtractTextPlugin({
filename: '[name].bundle.css'
})
You have 2 rules for both css and sass.
I think in your case you only need one:
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
and like you said, you should import the scss files in the js files import './css/app.scss'

Categories