i'm facing a problem with webpack 4 content load, how i used to do with jquery.
Here is what i'm trying to do with webpack 4
let say i have a page setting.html
<link rel="stylesheet" href="setting.css">
<div id="settingContent">
<!-- content -->
</div>
<script src="setting.js"></script>
on click of setting tab i want to load this page into index.html, #pageContent
index.html
<div id="pageContent">
</div>
with jquery i used to do it as shown below.
$('setting_tab').on('click',function(){
$('#pageContent').load('setting.html');
});
below is my webpack config file looks like
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['babel-polyfill', './src/js/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
Related
I'm using pug as my Node.JS view engine.
And I'm bundling my javascript files using webpack with hashname for cache busting.
The problem here is that I don't know how to include the bundled javascript file name in my pug template because every time it generates a new hash name.
How can I get the hash name generated from webpack and include it in my pug file?
This is how it should include the script file:
doctype html
html
include _head
body
script(src='/_bundle/main.649c4c4e6c8076189257.js')
My webpack.config.js
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
mode: "production",
entry: "./src/_public/js/index.js",
output: {
filename: "main.[contenthash].js",
path: path.resolve(__dirname, "src/_public/_bundle"),
},
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", "css-loader", "sass-loader",
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filetype: "pug",
}),
new HtmlWebpackPlugin({
filename: "./src/views/base.pug",
}),
],
}
Configure HtmlWebpackPlugin and HtmlWebpackPugPlugin properly:
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
module.exports = {
mode: "production",
entry: "./src/_public/js/index.js",
output: {
filename: "main.[contenthash].js",
path: path.resolve(__dirname, "src/_public/_bundle"),
},
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", "css-loader", "sass-loader",
],
},
],
},
plugins: [
new HtmlWebpackPugPlugin(),
new HtmlWebpackPlugin({
template: './src/views/base.pug',
filename: 'layout.pug',
}),
],
}
Install npm i HtmlWebpackPugPlugin. You will find the js and css references in the layout.pug file.
Actual solution for 2022.
Install the pug-plugin:
npm i -D pug-plugin
Using the pug-plugin:
the Webpack entry-point is the Pug file
all source scripts (JS/TS) can be loaded via require() in Pug
all source styles (CSS/SCSS) can be loaded via require() in Pug
Webpack config for Pug + JS + SCSS:
const path = require('path');
const PugPlugin = require('pug-plugin');
module.exports = {
output: {
path: path.join(__dirname, 'dist/'),
filename: 'js/[name].[contenthash:8].js' // output hashed filename of JS
},
entry: {
// define Pug files in entry:
index: './src/views/index.pug', // => index.html
about: './src/views/about/index.pug' // => about.html
// ...
},
plugins: [
// enable using Pug files as entry point
new PugPlugin({
extractCss: {
filename: 'css/[name].[contenthash:8].css' // output hashed filename of CSS
},
})
],
module: {
rules: [
{
test: /\.pug$/,
loader: PugPlugin.loader, // the Pug loader
},
{
test: /\.(css|sass|scss)$/,
use: ['css-loader', 'sass-loader']
},
],
},
};
Pug file ./src/views/index.pug:
doctype html
html
head
//- load source styles via require()
link(href=require('./path/to/scss/styles.scss') rel='stylesheet')
body
h1 Hello Pug!
//- load source scripts via require()
script(src=require('./path/to/js/index.js'))
Generated HTML:
<html>
<head>
<link href="/css/styles.f57966f4.css" rel="stylesheet">
</head>
<body>
<h1>Hello Pug!</h1>
<script src="/js/index.b855d8f4.js"></script>
</body>
</html>
When I run webpack server, Below config by default opens index.html available in public folder.
so, Instead of index.html, I want to create another.html or may be like a folder inside which an html eg. public/someFolder/another.html and want to open it, when webpack server is run.
how to run a different html file instead of index.html when webpack server runs?
webpack.config.js
const path = require("path");
module.exports = {
entry: "./myFile.js",
output: {
path: path.join(__dirname, "public"),
filename: "bundle.js",
},
module: {
rules: [
{
loader: "babel-loader",
test: /\.js$/,
exclude: /node_modules/,
},
{
test: /\.s?css$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
devtool: "cheap-module-eval-source-map",
devServer: {
contentBase: path.join(__dirname, "public"),
historyApiFallback: true,
},
};
Have a look at HtmlWebpackPlugin
You can specify a custom path and a custom .html file.
output: {
filename: './dist/subdirectory/myindex.html'
},
plugins: [new HtmlWebpackPlugin()]
The default is of course index.html
I am new to Webpack and not so experienced in JavaScript either. I'm trying to set up a new project for the JS text editor. However, I noticed that after setting up the first addEventListener for the #btn button, the event gets fired twice.
I don't think that this behaviour is related to the event itself, since I have created three console.log functions. One is outside the eventListener, two remaining is inside. All of the three functions get console logged twice in the browsers console, which leads me to think that this might be related to Webpack config.
If anyone has a clue or and advice, please help.
HTML:
<main class="main__content">
<article class="text__editor-wrapper">
<h1 class=" ">Text Editor</h1>
<div class="toolbar">
<button id="btn" class="toolbar__option"><span class="fas fa-bold fa-2x"></span></button>
</div>
<div class="text__editor" contenteditable="true"></div>
</article>
</main>
index.js:
import "./scss/style.scss";
import '#fortawesome/fontawesome-free/css/all.css';
import '#fortawesome/fontawesome-free/js/all.js';
const btn = document.querySelector("#btn");
function format(command, value) {
document.execCommand(command, false, value);
}
console.log("Outside")
btn.addEventListener('click', function(e) {
e.preventDefault();
console.log("inside");
console.log(e.target);
format('bold');
});
webpack config file:
const path = require("path"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
BrowserSyncPlugin = require("browser-sync-webpack-plugin"),
MiniCssExtractPlugin = require("mini-css-extract-plugin"),
UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
optimization: {
minimizer: [new UglifyJsPlugin()]
},
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 900
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.(svg|eot|woff|woff2|ttf)$/,
use: [{
loader: "file-loader"
}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: "url-loader"
}]
},
{
test: /\.(sass|scss|css)$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
}
You haven't given us your full HTML file, but I suspect this is where the problem lies.
Check your final (post-Webpack) index.html file - I suspect you're importing the main.js bundle in a <script> tag and also including the bundled JS.
This is because you're using Webpack to bundle your HTML (the HtmlWebpackPlugin plugin) and also creating a bundle (main.js) which you're importing somewhere in your HTML.
Im stuck and can't get to work my webpack configuration for loading images with src attribute from HTML. I cloned a repo with full setup of webpack, but I know there is a way to simply customize and load images directly from HTML.
Webpack.config.js file:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js"
},
output: {
path: path.join(__dirname, "../build"),
filename: "[name].bundle.js"
},
mode: "development",
devServer: {
contentBase: path.join(__dirname, "../build"),
compress: true,
port: 3000,
overlay: true
},
devtool: "cheap-module-eval-source-map",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader" // transpiling our JavaScript files using Babel and webpack
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"postcss-loader", // Loader for webpack to process CSS with PostCSS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
{
test: /\.(png|svg|jpe?g|gif)$/,
use: [
{
loader: "file-loader", // This will resolves import/require() on a file into a url
and emits the file into the output directory.
options: {
name: "[name].[ext]",
outputPath: "assets",
}
},
]
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: {
attrs: ["img:src", ":data-src"],
minimize: true
}
}
}
]
},
plugins: [
// CleanWebpackPlugin will do some clean up/remove folder before build
// In this case, this plugin will remove 'dist' and 'build' folder before re-build again
new CleanWebpackPlugin(),
// The plugin will generate an HTML5 file for you that includes all your webpack bundles
in
the body using script tags
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
Before this project I was able to make that images would simply load from HTML but now ironicly im stuck and can't get this working.
Any help will be very appriciated.
When loading a image directly form HTML, I get the following error:
Error: Child compilation failed:
Module not found: Error: Can't resolve '
./src/assets/images/portret.jpg' in '/home/viktoras/www/sites/painter-new/src':
You can do this:
<img src="<%=require('./src/assets/logo.png')%>">
Plugin Conf
$new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html'
}),
I'm writing a react app and everything works fine when I navigate to localhost:3000, but when I try to go to localhost:3000/foo/page, I get an error message that tells me localhost:3000/foo/bundle.js cannot be loaded.
To me, this looks like a problem with Webpack looking in the wrong place for bundle.js, but I'm not sure. How do I get the app to always look at localhost:3000 for bundle.js?
This is some of my webpack config.
var TARGET = process.env.npm_lifecycle_event;
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'dist');
process.env.BABEL_ENV = TARGET;
var common = {
entry: APP_PATH,
output: {
path: BUILD_PATH,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel'],
include: APP_PATH
},
{
test: /\.svg$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
},
{
test: /\.png$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
},
{
test: /\.ico$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'foobar',
template: path.resolve(APP_PATH, 'index.html'),
favicon: path.resolve(APP_PATH, 'images', 'favicon.ico')
})
]
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
include: APP_PATH
}
]
},
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
port: 3000,
progress: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
});
}
Add output.publicPath: '/' to your webpack config.
output: {
path: BUILD_PATH,
publicPath: '/',
filename: 'bundle.js'
}
HtmlWebpackPlugin most probably generates the file which have:
<script src="bundle.js"></script>
Setting up output.publicPath: '/' will make it:
<script src="/bundle.js"></script>
From Webpack Config page:
output.publicPath
The publicPath specifies the public URL address of
the output files when referenced in a browser. For loaders that embed
or tags or reference assets like images, publicPath is
used as the href or url() to the file when it’s different then their
location on disk (as specified by path). This can be helpful when you
want to host some or all output files on a different domain or on a
CDN. The Webpack Dev Server also takes a hint from publicPath using it
to determine where to serve the output files from. As with path you
can use the [hash] substitution for a better caching profile.