How open image with tag a? - html

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>

Related

Inline all html tags with appropriate style from a stylesheet using html-inline-css-webpack-plugin

In order to send email from an application I develop, due to smtp client restrictions,
I would like to inline every style class from my CSS in each tags in my final html template using Webpack. In my case I can inline all the stylesheet in the one div but my aim is to get every tag of the style to be filled with the appropriate style.
Here is my webpack.config :
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HTMLInlineCSSWebpackPlugin = require("html-inline-css-webpack-plugin").default;
module.exports = {
mode: 'development',
entry: [
'./src/main.js',
],
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
}),
new HtmlWebpackPlugin({
filename: 'review.html',
template: './src/templates/models/review.pug',
}),
new HtmlWebpackPlugin({
filename: 'access_request.html',
template: './src/templates/models/domain_access_request.pug',
}),
new HtmlWebpackPlugin({
filename: 'analytics_alert.html',
template: './src/templates/models/analytics_alert.pug',
}),
new HtmlWebpackPlugin({
filename: 'battery_pb.html',
template: './src/templates/models/battery_pb.pug',
}),
new HtmlWebpackPlugin({
filename: 'deco_module_cloud.html',
template: './src/templates/models/deco_module_cloud.pug',
}),
new HtmlWebpackPlugin({
filename: 'stock_pb.html',
template: './src/templates/models/stock_pb.pug',
}),
new HTMLInlineCSSWebpackPlugin({
replace: {
target: 'tbody',
removeTarget:true
}
}),
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.scss$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'sass-loader'
}
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: true,
includePaths: [
path.resolve(__dirname, './src/templates/assets/scss')
]
}
},
],
},
{
test: /\.pug$/,
use: [
'pug-loader'
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},
};
Hope you understood my issue.

How to automatically add css imports in all generated html files?

I'm generating multiples *.html files in the dist folder of my project (copied with file-loader). The import of styles.css (generated from scss files from my src folder) is present in the generated index.html but not in the other generated html files which are located in my src/pages (and also generated in the dist folder).
How can I add the styles.css import in all generated html files or even better in all targeted html files?
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin'); // to minify JS
module.exports = {
entry: ['#babel/polyfill', './src/js/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
optimization: {
//https://webpack.js.org/plugins/mini-css-extract-plugin/
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
output: {
comments: /#license/i,
},
},
extractComments: false,
}),
new OptimizeCSSAssetsPlugin({})
], // utilisés pour minifier le css généré en Production
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.s[ac]ss$/i,
chunks: 'all',
enforce: true,
},
},
},
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: false
}
}),
new MiniCssExtractPlugin({
filename: '[name].css'
}),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
//{ from: 'other', to: 'public' },
]),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.(html)$/i,
loader: 'html-loader',
options: {
attributes: false,
interpolate: true,
},
},
{
test: /\.s[ac]ss$/i,
use: [
{loader: MiniCssExtractPlugin.loader},
//'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
'postcss-loader',
'sass-loader',
],
},
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {}
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images',
esModule: false,
}
}
]
},
{
test: /\.html$/,
loader: 'file-loader',
options: {
name: '[name].[ext]'
},
exclude: [
path.resolve(__dirname, 'src/index.html'),
path.resolve(__dirname, 'src/fragments')
]
},
]
}
};
Thank in advance for your help.

Webpack 4: error with malformatted json

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)

Add assets folder in mern io

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.

Webpack doesn't bundle images referenced only in HTML

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.