Answer the question
In order to leave comments, you need to log in
Webpack 5 how to pull images from html?
Good afternoon!
I'm learning Webpack 5 and ran into a problem how to pull images from html.
There is such a test project (plugin HtmlWebpackPlugin is used ):
File system:
webpack.config.dev.js
const path = require('path');
const fs = require('fs');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
function generateHtmlPlugins(templateDir) {
const templateFiles = fs.readdirSync(path.resolve(__dirname, templateDir));
return templateFiles.map(item => {
const parts = item.split('.');
const name = parts[0];
const extension = parts[1];
return new HtmlWebpackPlugin({
filename: `${name}.html`,
template: path.resolve(__dirname, `${templateDir}/${name}.${extension}`),
inject: 'body',
scriptLoading: 'defer',
publicPath: '/'
})
})
}
const htmlPlugins = generateHtmlPlugins('src/views')
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src/js/main.js'),
output: {
publicPath: '/',
clean: true,
filename: 'js/[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
assetModuleFilename: 'img/[name][ext]'
},
devtool: 'inline-source-map',
devServer: {
publicPath: '/',
historyApiFallback: true,
contentBase: path.resolve(__dirname, 'dist'),
open: true,
compress: true,
port: 8080,
},
plugins: [new MiniCssExtractPlugin({
filename: 'css/[name].css'
})].concat(htmlPlugins),
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
};
<% if (process.env.NODE_ENV === 'development') { %>
<%= require('html-loader!../top.html').default %>
<% }else { %>
<% for (var css in htmlWebpackPlugin.files.css) { %>
<link href="<%= htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
<% } %>
<% } %>
<img src="../img/E75-TS_2.png" alt="">
<% if (process.env.NODE_ENV === 'development') { %>
<%= require('html-loader!../bottom.html').default %>
<% }else { %>
<% for (var js in htmlWebpackPlugin.files.js) { %>
<script src="<%= htmlWebpackPlugin.files.js[js] %>"></script>
<% } %>
<% } %>
<img src="./img/E75-TS_2.png" alt="">
Answer the question
In order to leave comments, you need to log in
Found a solution that works
<img src="<%=require('../img/E75-TS_2.png')%>" alt="">
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question