To be brief, here i have my webpack (below,i put the code concerned).
Actually, webpack create the image folder with an svg of the font, but not the svg images. (screenshot below)
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: [
'style-loader', // Creates `style` nodes from JS strings
'css-loader', // Translates CSS into CommonJS
'sass-loader', // Compiles Sass to CSS
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'image/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|otf|eot)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'font/'
}
}
]
}
]
},
and here is my HTML :
<div class="cc-header__left">
<img src="image/LOGO.svg" alt="logo conseil constitutionnel" />
<p class="cc-header__logoName"> Élection présidentielle <span>2022</span></p>
</div>
You may try to install html-loader and add new loader to config
module: {
rules: [
// ...
{
test: /\.html$/i,
use: {
loader: 'html-loader',
}
}
]
}
i found this solution :
const importAll = require =>
require.keys().reduce((acc, next) => {
acc[next.replace("./", "")] = require(next);
return acc;
}, {});
const images = importAll(
require.context("./image", false, /\.(png|jpe?g|svg)$/)
);
i've added this code to my app.js
Related
I am currently switching a web app to have its assets bundled using Webpack. Bundling JS and CSS was somewhat straightforward. Then came the turn of images. My question is how one can approach bundling images.
In particular, suppose I have static_src from which everything originates and static_compiled into which the bundled output is placed. I would like the image contents of static_src/img to move into static_compiled/img. How does one accomplish this?
On another note, is this a sensible approach or am I misunderstanding some philosophy behind Webpack and misusing it?
Current config is roughly like this:
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: { index: path.resolve(__dirname, "static_src", "index.js") },
output: {
path: path.resolve(__dirname, "static_compiled"),
publicPath: "/static/", // Should match Django STATIC_URL
filename: "[name].js", // No filename hashing, Django takes care of this
chunkFilename: "[id]-[chunkhash].js", // DO have Webpack hash chunk filename, see below
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
rules: [
{
test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
{
test: /\.scss$/, use: ["style-loader", "css-loader", "sass-loader"]},
{
test: /\.css$/, use: ["style-loader", "css-loader"]},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader'},
{
test: /\.svg$/,
loader: 'svg-inline-loader'},
/* {
test: /\.(ico|png|jpg|gif)$/,
loader: 'file-loader'} */
{
test: /\.(ico|png|svg|jpg|gif|jpe?g)$/,
use: [
{
options: {
name: "[name].[ext]",
outputPath: "img/"
},
loader: "file-loader"
}
]
}
],
},
resolve: {
alias: {
shared: path.resolve(__dirname, 'node_modules', 'bower_components')
},
extensions: ['.js', '.ts', 'jsx', 'tsx']
},
devServer: {
writeToDisk: true, // Write files to disk in dev mode, so Django can serve the assets
}
}
The code I ended up using looks something like this.
plugins section:
plugins: [...
new CopyPlugin({
patterns: [
{
from: path.resolve(__dirname, `static_src/img`),
to: 'img',
}
]
}),
module-rules section:
module: {
rules: [
{ ...
test: /\.(ico|png|jpg|gif|jpe?g)$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "img/"
}
}
]
}
I'm learning by making my own projects and currently I am designing my own MEAN-stack app. This app uses Webpack and in the past I was unable to show any images.
Then I installed a URL-loader and now I am able to show images when I enter the local URL in the src attribute of an img element.
However, now I am trying to use a local image for a background-image property in SCSS and it is not showing at all. The code below shows the SCSS code, HTML code and what I have in my Webpack file. What do I need to do to fix this?
SCSS file: profile-nav.component.SCSS
#import "../../SASS/abstracts/variables";
#import "../../SASS/abstracts/mixins";
.img-container {
height: 33.3333vh;
position: relative;
background-image: url("../../images/slytherin-logo.jpg");
background-size: cover;
img {
border-radius: 50%;
#include center-horizontal-vertical;
height: 80%;
width: 25%;
}
}
HTML file: profile-nav.component.html. I am able to show the img image, but not the background image I entered in the SCSS file
<div class="img-container">
<img src="../../images/profile_picture.jpg" alt="jooo">
</div>
Webpack: webpack.config.ts
var webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app': './assets/app/main.ts'
},
resolve: {
extensions: ['.js', '.ts']
},
module: {
rules: [
{
test: /\.html$/,
use: [{ loader: 'html-loader' }]
},
{
test: /\.css$/,
use: [{ loader: 'raw-loader' }]
},
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: { limit: 40000 }
},
'image-webpack-loader'
]
}
],
exprContextCritical: false
}
};
EDIT this is what my webpack.config file looks like after adjustments
var webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app': './assets/app/main.ts'
},
resolve: {
extensions: ['.js', '.ts']
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader' ] // <------
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'] // <-----
},
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
'file-loader'
'image-webpack-loader'
]
}
],
exprContextCritical: false
}
};
You missing some loaders:
rules: [
{
test: /\.html$/,
use: [{ loader: 'html-loader' }]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader' ] // <------
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'] // <-----
},
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: { limit: 40000 }
},
'image-webpack-loader'
]
}
],
I'm using webpack 4 (4.6.0), I don't use the json-loader as it is my understanding that webpack handle this by default now.
When I'm working locally (I'm using serve from browser-sync to create a local dev-server), and I modified a JSON file wrongly (the JSON is not formatted correctly after my hcange), webpack exit with an error (instead of just telling me that there is an error on the json file and continue when I fix it).
Anyone experienced this issue (and knows how to solve it)?
This is the error I'm getting:
/code/program/node_modules/webpack/lib/JsonGenerator.js:10
JSON.stringify(data).replace(
^
TypeError: Cannot read property 'replace' of undefined
at stringifySafe (/code/program/node_modules/webpack/lib/JsonGenerator.js:10:22)
at JsonGenerator.generate (/code/program/node_modules/webpack/lib/JsonGenerator.js:36:53)
at NormalModule.source (/code/program/node_modules/webpack/lib/NormalModule.js:413:33)
at ModuleTemplate.render (/code/program/node_modules/webpack/lib/ModuleTemplate.js:43:31)
at modules.map.module (/code/program/node_modules/webpack/lib/Template.js:157:28)
at Array.map (<anonymous>)
at Function.renderChunkModules (/code/program/node_modules/webpack/lib/Template.js:154:28)
at HotUpdateChunkTemplate.render (/code/program/node_modules/webpack/lib/HotUpdateChunkTemplate.js:48:34)
at compilation.hooks.additionalChunkAssets.tap (/code/program/node_modules/webpack/lib/HotModuleReplacementPlugin.js:165:48)
at SyncHook.eval (eval at create (/code/program/node_modules/tapable/lib/HookCodeFactory.js:17:12), <anonymous>:7:1)
at SyncHook.lazyCompileHook [as _call] (/code/program/node_modules/tapable/lib/Hook.js:35:21)
at hooks.optimizeTree.callAsync.err (/code/program/node_modules/webpack/lib/Compilation.js:944:37)
at AsyncSeriesHook.eval [as callAsync] (eval at create (/code/program/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:6:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/code/program/node_modules/tapable/lib/Hook.js:35:21)
at Compilation.seal (/code/program/node_modules/webpack/lib/Compilation.js:890:27)
at hooks.make.callAsync.err (/code/program/node_modules/webpack/lib/Compiler.js:481:17)
at _done (eval at create (/code/program/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)
at _err1 (eval at create (/code/program/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:32:22)
at _addModuleChain (/code/program/node_modules/webpack/lib/Compilation.js:758:12)
at processModuleDependencies.err (/code/program/node_modules/webpack/lib/Compilation.js:697:9)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
EDIT: Find below my webpack config:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackNotifierPlugin = require('webpack-notifier');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {},
resolve: {
modules: [
path.resolve(__dirname),
path.resolve(__dirname, 'node_modules')
],
extensions: [ '.js' ],
alias: {
app: 'client/app',
common: 'client/app/common',
components: 'client/app/components'
}
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
publicPath: '/',
path: path.resolve(__dirname, 'client')
},
mode: 'development';
module: {
rules : [
{
test: /\.js$/,
exclude: [ /app\/lib/, /node_modules/],
enforce: 'pre',
use: [
{
loader: 'eslint-loader',
options: {
failOnWarning: false,
failOnError: true
}
},
],
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
]
},
{
test: /\.(scss|sass)/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
includePaths: [ path.resolve(__dirname, './client/app') ],
sourceMap: true
}
},
]
},
{
test: /\.html$/,
use: [
{
loader: 'raw-loader',
options: {
minimize: false
}
}
]
},
{
test: /\.js$/,
exclude: [ /app\/lib/, /node_modules/],
use: [
{
loader: 'ng-annotate-loader?add=true&single_quotes=true'
},
{
loader: 'babel-loader'
}
]
},
{
test: /\.svg/,
use: [
{
loader: 'svg-url-loader'
}
]
},
{
test: /\.(png|jpg)$/,
use: [
{
loader: 'url-loader?limit=1024'
}
]
},
{
test: /\.woff$/,
use: [
{
loader: 'url-loader?limit=65000&mimetype=application/font-woff&name=public/fonts/[name].[ext]'
}
]
},
{
test: /\.woff2$/,
use: [
{
loader: 'url-loader?limit=65000&mimetype=application/font-woff2&name=public/fonts/[name].[ext]'
}
]
},
{
test: /\.[ot]tf$/,
use: [
{
loader: 'url-loader?limit=65000&mimetype=application/octet-stream&name=public/fonts/[name].[ext]'
}
]
},
{
test: /\.eot$/,
use: [
{
loader: 'url-loader?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/fonts/[name].[ext]'
}
]
}
],
noParse: [
'/node_modules/d3-cloud/build/d3.layout.cloud.js',
]
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require("./package.json").version)
}),
new webpack.ProvidePlugin({
c3: 'c3',
Bugsnag: 'bugsnag-js'
}),
// This is used to have a banner shown to the user to "Add to home screen"
// It works with the service-worker called in app.js
new CopyWebpackPlugin([
{
from: './config',
to: path.resolve(__dirname, 'dist/')
},
{
from: './assets/**/*',
to: path.resolve(__dirname, 'dist/')
},
]),
// Injects bundles in your index.html instead of wiring all manually.
// It also adds hash to all injected assets so we don't have problems
// with cache purging during deployment.
new HtmlWebpackPlugin({
template: 'client/indexMockBackEnd.html',
//template: 'client/index.html',
inject: 'body',
hash: true,
favicon: 'client/app/common/favicon/favicon.ico'
}),
new webpack.DefinePlugin({
ENVIRONMENT: JSON.stringify('development'),
BROCHURE_HOME_URL: JSON.stringify(`https://pl.dev`)
}),
// Adds webpack HMR support. It act's like livereload,
// reloading page after webpack rebuilt modules.
// It also updates stylesheets and inline assets without page reloading.
new webpack.HotModuleReplacementPlugin(),
// displays desktop notifications on MacOS
new WebpackNotifierPlugin(),
],
optimization: {
namedModules: true, // NamedModulesPlugin()
splitChunks: {
chunks: "all"
},
runtimeChunk: true,
concatenateModules: true //ModuleConcatenationPlugin
}
};
This was a bug in webpack.
See details of the bug here: https://github.com/webpack/webpack/issues/7082
See pull request to fix it here: https://github.com/webpack/webpack/pull/7590
It is now fixed (as of July 2018)
i am using mern.io my web pack config is looks like :
var webpack = require('webpack');
var cssnext = require('postcss-cssnext');
var postcssFocus = require('postcss-focus');
var postcssReporter = require('postcss-reporter');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: {
app: [
'eventsource-polyfill',
'webpack-hot-middleware/client',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
'./client/index.js',
],
vendor: [
'react',
'react-dom',
],
},
output: {
path: __dirname,
filename: 'app.js',
publicPath: 'http://0.0.0.0:8888/',
},
resolve: {
extensions: ['', '.js', '.jsx'],
modules: [
'client',
'node_modules',
],
},
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader',
}
, {
test: /\.css$/,
include: /node_modules/ ,
loaders: ['style-loader', 'css-loader'],
}
, {
test: /\.jsx*$/,
exclude: [/node_modules/, /.+\.config.js/],
loader: 'babel',
}, {
test: /\.(jpe?g|gif|png|svg)$/i,
loader: 'url-loader?limit=10000',
}, {
test: /\.json$/,
loader: 'json-loader',
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=1&minetype=application/font-woff" },
{ test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=1&minetype=application/font-woff" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=1' }
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.js',
}),
new webpack.DefinePlugin({
'process.env': {
CLIENT: JSON.stringify(true),
'NODE_ENV': JSON.stringify('development'),
}
}),
],
postcss: () => [
postcssFocus(),
cssnext({
browsers: ['last 2 versions', 'IE > 10'],
}),
postcssReporter({
clearMessages: true,
}),
],
};
i would like to add a custom css file which resides in : /public/assets/css/custom.css; Then what would be my configurations?
i can import css file in node_modules eg : require('rc-slider/assets/index.css');
as it says in the config :
{
test: /\.css$/,
include: /node_modules/ ,
loaders: ['style-loader', 'css-loader'],
}
i have replicated the entry with :
{
test: /\.css$/,
include: /public/ ,
loaders: ['style-loader', 'css-loader'],
}
but not working
There can be two approach to handle this situation.
1.
You can use the following to add public folder to serve static files.
app.use(express.static('public'));
And then you can add the file in the html if you are using server side rendering.
2.
You can put this file on client side and simply import the file at the entry point of webpack on client side.
And webpack will automatically include it using style loader.
I've encountered a strangle problem which I'm unable to solve on my own. My webpack config doesn't compile imagenes from my source directory to build directory when they are only referenced from in HTML, while it does compile imagenes referenced in css without any problems. Here's my webpack.config.file:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
bundle: './js/app.js',
vendor: 'jquery'
},
output: {
path: path.resolve('./build'),
filename: "[name].js",
publicPath: './build/'
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity })],
watch: true,
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpg|gif|svg)$/,
loaders: [{
loader: 'file-loader',
options: {
name: 'img/[name].[ext]',
context: '',
}
},
{
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 5,
},
pngquant: {
quality: '75-90',
speed: 5,
},
}
}
]
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'url-loader'
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':img-src']
}
}
}
]
}
};
The html-loader will only process the attributes that are specified in the attrs option in the form of <tag>:<attribute>. You are using :img-src, that means match any tag (because the value before the : is empty) and process the attribute img-src.
What you want is to process the src attribute of the img tag:
{
loader: 'html-loader',
options: {
attrs: ['img:src']
}
}
That is already the default of html-loader (see README - Usage), which means that you don't need to configure that option.