For some reason my webpack configuration is loading the images that comes from my SCSS files but not the ones that come from the HTML files. Also when I run the BUILD command in order to deliver my prod archives it does not create the "img" folder. To be honest I'm pretty new with webpack 4 and I guess there's a couple of steps that I'm not including on the WP config file.
This is my webpack.dev.js
This is the prod folder structure that I would want to create:
dist
|----img
|----css
|----js
a.html
b.html
c.html
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
entry: {
main: "./src/js/scripts.js"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/[name].[hash].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: [
"style-loader",
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader"
]
},
{
test: /\.(png|jpg|gif)$/,
use: ["url-loader"]
}
]
},
devServer: {
port: 8080
},
plugins: [
new CleanWebpackPlugin("dist", {}),
new MiniCssExtractPlugin({
filename: "css/style.[contenthash].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
inject: false,
hash: true,
filename: "index.html"
}),
new HtmlWebpackPlugin({
template: "./src/actualitat.html",
inject: false,
hash: true,
filename: "actualitat.html"
}),
new HtmlWebpackPlugin({
template: "./src/projectes.html",
inject: false,
hash: true,
filename: "projectes.html"
})
]
};
This is the way im loading both css and js on my html files:
<link
rel="stylesheet"
href="<%=htmlWebpackPlugin.files.chunks.main.css %>"
/>
<script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
I have a "scripts.js" js file where I import the files like this:
import "../scss/style.scss";
import "../img/searchBar-icon.png";
import "../img/townHall.png";
import "../img/icon-title.png";
UPDATE:
I have change the way im loading images using the "file-loader" loader:
{
test: /\.(png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
outputPath: "img/",
name: "[name][hash].[ext]"
}
}
}
Now all of my images are being copied to the "img" folder which is good, problem is that all the names of the files have hashes now (which make sense since I'm telling the loader to add them) and they're not loading on my html files.
Can you try the following for loading the images?
{
test: /\.(jpe?g|png|gif|ico)$/i,
use: ["file-loader?name=[name].[hash].[ext]"]
}
Related
To create my page i use webpack. In page i want show multiple image. On internet i found library "lightbox2". This library is used for click image and popup. The library have simple example like this:
<a
class="example-image-link"
href="../image/bed-small.jpg" -- not work
href="./469cccac29babd05add3a0b2d23abf0d.jpg" -- work
data-lightbox="example-1"
><img class="example-image" src="../image/bed-small.jpg" alt="image-1" --here work
/></a>
Img src work great and i see picture on my page. When i click on image popup work but image never loaded. I used dev-tools and i see that my image is download with that name '469cccac29babd05add3a0b2d23abf0d.jpg'. So i copy and i see my image. My question is how generate that file name dynamic in my html file ? Below i add my webpack.conf
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
},
entry: {
main: './js/index.js',
fontAwesome: './js/fontAwe.js',
fontSolid: './js/fontSolid.js',
fontRegular: './js/fontRegular.js',
galery: './js/galery.js',
},
plugins: [
new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
new HtmlWebpackPlugin({
title: 'none',
template: './index.html',
inject: true,
chunks: ['main', 'fontAwesome', 'fontSolid', 'fontRegular'],
filename: 'index.html',
}),
new HtmlWebpackPlugin({
title: 'none',
template: './pages/galeria.html',
inject: true,
chunks: ['galery'],
filename: 'galeria.html',
}),
],
output: {
publicPath: '/',
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
// Prefer `dart-sass`
implementation: require('sass'),
},
},
],
},
{
test: /\.html$/i,
loader: 'html-loader',
},
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
},
},
],
},
],
},
};
My dev-tool
No longer current. I found solution. Import image to js file and changed href ;)
change name of photo and use:<div class=""><a src="></a>
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
So I just want to use some images in my React application, but images are not loading up. Some images are set up in CSS like that:
background-image: url('/../img/logo.png');
Another way I would like to use images in inside React components with
img tag, how would I go about doing this?
Here is my webpack config:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env) => {
const isProduction = env === 'production';
return {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../'
}
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
}]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "styles.css",
})
],
devtool: isProduction ? 'source-map' : 'inline-source-map',
devServer: {
contentBase: path.resolve(__dirname, 'public'),
historyApiFallback: true,
publicPath: '/dist/'
},
performance: {
hints: process.env.NODE_ENV === 'production' ? "warning" : false
},
}
};
index.html inside public folder:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kinnisvara ABC</title>
<link rel="stylesheet" href="/dist/styles.css" type="text/css">
</head>
<body>
<div id="app"></div>
<script src="/dist/bundle.js"></script>
</body>
</html>
CSS is loading up, but images are not.
Pictures of my file structure:
Can anyone help me with that, please?
Have 2 way
Use webpack url-loader
Add this line to rules module in webpack file
{ test: /.(png|jpg|woff|woff2|eot|ttf|svg|gif)$/, loader: 'url-loader?limit=1024000' }
Use serve to point image
{
test: /\.(gif|png)$/, //Customise according to your need
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
name: PATH + '.[ext]' //Path will be assets or image path
}
}
]
}
configure url-loader in webpack configuration like this.
You didn't added image loader like css so try to add that
test: /\.(gif|jpe?g|png)$/,
i want to separate my project file to multi files.
with sass and JavaScript import, i can do that just for styles and scripts.
but i want to separate HTML files too.
i dont use any frameworks just webpack.
according to webpack documentation, we can do that with interpolation
https://webpack.js.org/loaders/html-loader/#interpolation
require("html-loader?interpolate!./file.html");
<div>${require('./components/gallery.html')}</div>
but i got error:
Cannot find module 'html-loader?interpolate!./file.html'
my webpack config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const webpack = require('webpack');
require("html-loader?interpolate!./file.html");
module.exports = {
devtool: 'source-map', // to see source map of scss and ts
entry: [ // root files to load
'./node_modules/material-design-lite/material.min.js',
'./src/scripts/main.ts',
'./src/index.html',
'./src/styles/main.scss',
],
mode: 'development',
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: 'ts-loader',
options: {
transpileOnly: false
}
},
{ // to auto refresh index.html and other html
test: /\.html$/,
loader: "raw-loader",
exclude: /node_modules/,
},
{
test: /\.html$/,
use: [ {
loader: 'html-loader',
}],
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "sass-loader", options: {
sourceMap: true
}
}]
},
{ // for images and fonts in scss file
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
}
]
},
resolve: {
extensions: ['.ts', '.js', '.json'],
plugins: [
// to get access of custom typescript paths. (e.g. _app/XXX/XX or #app/XXX/XX)
new TsconfigPathsPlugin({ configFile: __dirname + "/tsconfig.json" })
]
},
output: {
filename: "./bundle.js",
path: path.resolve(__dirname, './build'),
},
plugins: [
// use for html pre complier like jade
// new HtmlWebpackPlugin({
// filename: 'index.html',
// path: path.resolve(__dirname, './build'),
// template: './src/index.jade',
// inject: 'body',
// }),
new HtmlWebpackPlugin({
template: './src/index.html'
}),
// copy assets folder to access file from html or as http request
new CopyWebpackPlugin([{
from: './src/assets',
to: path.resolve(__dirname, './build/assets')
}]),
// to use hot, inline (auto refresh) in config file. with out this we have to set as command of webpack-dev-server
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: path.resolve(__dirname, './build'),
hot: true, // for auto refresh
inline: true, // for auto refresh
port: 3000,
overlay: true // for show error on html
}
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Zoom.FM</title>
</head>
<body>
<div class="side-nav mdl-list">
<div>${require('./myfile.html')}</div>
</body>
</html>
how can i do that or how interpolation work?
I found answer :)
remove require("html-loader?interpolate!./file.html")
enable interpolate in webpack config
webpack config
{
test: /\.html$/,
use: [ {
loader: 'html-loader',
options: {
interpolate: true
}
}],
},
I'm very new to Webpack and I'm not certain how to handle LESS. I want to have many LESS files and I want them to compile into one CSS file after I run npm run build. This would result in a style.css file which includes everything.
My webpack.config.js looks like this:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules:
[
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.less$/,
use: [{
loader: "style-loader", // creates style nodes from JS strings
path: path.resolve(__dirname, 'src')
}, {
loader: "css-loader", // translates CSS into CommonJS
path: path.resolve(__dirname, 'src')
}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
plugins: [new HtmlWebpackPlugin()]
};
How exactly do I configure webpack to make it combine all LESS files into one CSS file?
You can use a plugin called extract-text-webpack-plugin to achieve this. According to their documentation, this plugin moves all the required *.css modules in entry chunks into a separate CSS file. So your styles are no longer inlined into the JS bundle, but in a separate CSS file (styles.css). Now of course, in your case, you will first have to parse your .less files to .css and then bundle them up into a single file.
You can modify your webpack config like so:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({ <---- Use the plugin here to extract the styles
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin(),
new ExtractTextPlugin("styles.css"),
]};
You can use extract-text-webpack-plugin to make one css file. But only do this for a production build not while you are developing.
I would look at using the Webpack less-loader. It covers a production build here