Answer the question
In order to leave comments, you need to log in
How do I properly load Webpack images in order to preserve the folder structure?
Hello! I recently started learning Webpack. There was such a problem: how can I process pictures correctly so that they can be connected without violating the folder structure.
src folder structure:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
const isDev = process.env.NODE_ENV === 'development';
const isProd = !isDev;
const cssLoaders = ext => {
const cfg = [{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: isDev,
reloadAll: true
}
}, 'css-loader'];
if(ext) {
ext.forEach( loader => cfg.push(loader) );
}
return cfg;
}
const optimization = () => {
const cfg = {
splitChunks: {
chunks: 'all'
}
};
if(isProd) {
cfg.minimizer = [
new OptimizeCssAssetsWebpackPlugin(),
new TerserWebpackPlugin()
];
}
return cfg;
}
module.exports = {
context: path.resolve(__dirname, 'src'),
mode: 'development',
entry: ['@babel/polyfill', './js/app'],
output: {
filename: isDev ? 'js/script.[hash].js' : 'js/script.js',
path: path.resolve(__dirname, 'dist')
},
optimization: optimization(),
devServer: {
port: 5000,
hot: isDev
},
devtool: isProd ? 'source-map' : '',
resolve: {
alias: {
icons: path.resolve(__dirname, 'src/icons/'),
},
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
use: cssLoaders(['sass-loader'])
},
/*{
test: /\.svg$/,
use: [
{
loader: 'file-loader',
options: {
name: 'icons/[name].[ext]'
}
}
]
},*/
{
test: /\.js$/,
exclude: /node_modules/,
loader: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env'
],
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-private-methods'
]
}
}
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
minify: {
collapseWhitespace: isProd
}
}),
new MiniCssExtractPlugin({
filename: isDev ? 'css/style.[hash].css' : 'css/style.css'
}),
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'src/icons'),
to: path.resolve(__dirname, 'dist/icons')
},
]
})
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question