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/"
}
}
]
}
Related
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
I just installed react, webpack, and babel into one of my projects (I used this tutorial https://medium.com/swlh/a-complete-webpack-setup-for-react-e56a2edf78ae but I tweaked a bit of the webpack.config.js file because it was giving errors) and now my css stylesheet for my html file doesn't link (when I type npm run start) and I'm not exactly sure why
This is how I link my stylesheet
<link rel="stylesheet" type="text/css" media="screen" href="index-styles.css">
This is my webpack.config.js
const path = require("path");
const autoprefixer = require("autoprefixer");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
chunkFilename: "[id].js",
publicPath: ""
},
resolve: {
extensions: [".js", ".jsx"]
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: "style-loader" },
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[name]__[local]___[hash:base64:5]"
},
sourceMap: true
}
},
{
loader: "postcss-loader"
// postcssOptions: {
// ident: "postcss",
// options: {
// }
// //plugins: () => [autoprefixer({})]
// }
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: "url-loader?limit=10000&name=img/[name].[ext]"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + "/src/index.html",
filename: "index.html",
inject: "body"
})
]
};
And right now my project structure is
assets
images
node_modules
src
|___index-styles.css (one I'm linking to index.html)
|___index.css (one used in index.js for tutorial)
|___index.html
|___index.js
.babelrc
package-lock.json
package.json
webpack.config.js
I am new to webpack, I followed directions in this link https://github.com/hardikkaji/angularjs-es6-starter-kit
I am using webpack 4 with angular 1.7
I am not able to resolve images.
ERROR in ./node_modules/angular-datatables/demo/basic/overrideLoadingTpl.html
Module not found: Error: Can't resolve './images/loading.gif' in '/home/user/workspace/webpack/angular-webpack/node_modules/angular-datatables/demo/basic'
My webpack.config.js is below
const config = {
mode: devMode ? 'development' : 'production',
entry: {
'vendor': './frontend/vendor.module.js', //seperates all 3rd party plugins like ui-router, retstangualr etc
'app': './frontend/index.main.js' //main entry point for angular js
},
devtool: devMode ? 'source-map': 'none',
output: {
filename: elixirConfig.js.outputFolder + '/[name].[hash].bundle.js',
//filename: 'libs/[name].[hash].bundle.js', //where to store the generated files all files will be generated inside a folder called libs
//path: path.resolve(__dirname, 'build')
path: path.resolve(__dirname, elixirConfig.buildPath)
},
module: {
rules: [
{
test: /.js$/, //check for file that ends with .js extension
exclude: /node_modules/, //do not check for files inside node_modules folder
loader: ['ng-annotate-loader', 'babel-loader'],
//presets: ['es2016'],
},
{
test: /.(scss)$/, //check for files that end with scss
use: [
devMode ? { loader: "style-loader" } : MiniCssExtractPlugin.loader,
{ loader: "css-loader", options: { minimize: true } },
{ loader: "sass-loader" },
]
},
// for fixing of loading bootstrap icon files
{
test: /.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000',
options: {
name: './fonts/[name].[ext]'
}
},
{
test: /.(woff(2)?|ttf|eot|svg)(\?v=\d+.\d+.\d+)?$/,
loader: 'file-loader',
options: {
name: './fonts/[name].[ext]'
}
},
{ test: /.html$/, include: /node_modules/, loader: 'html-loader' },
]
},
I have used angular builders and created custom webpack.config.js
I am trying to use webpack-rtl-plugin.
Following are my custom-webpack.config.js
module.export = {
entry: {
app: path.join(__dirname, './src/main.ts')
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
// for dev we simply use the style-loader combined with
// the rtl-css loader
loaders: ['style-loader', 'rtl-css-loader']
}
]
}
};
But I am getting Following error
Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi"
What is the cause of this? Any alternate solutions?
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.