Webpack - Best way to update HTML to include latest [hashed] bundles - javascript

I'm using webpack to generate hashed bundle filenames.
Assuming I'm using static HTML, CSS & JS, what is the best way to automatically update index.html to point to the latest bundles?
For example,
update:
<script src="e8e839c3a189c25de178.app.js"></script>
<script src="c353591725524074032b.vendor.js"></script>
to:
<script src="d6cba2f2e2fb3f9d98aa.app.js"></script>
<script src="c353591725524074032b.vendor.js"></script> // no change
automatically everytime a new bundle version is available.

Amazingly, this is what the html-webpack-plugin is for.
var webpack = require('webpack');
var path = require('path');
var HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = function(env) {
return {
entry: {
main: './src/index.js',
vendor: 'moment'
},
output: {
filename: '[chunkhash].[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
new HTMLWebpackPlugin({
tempate: path.join(__dirname, './src/index.html')
})
]
}
};
This generates an index.html in the dist directory that includes the script's in the correct order.
youtube example

Related

Why "npm run build" does not generate *.asset.php when working with #wordpress/scripts?

I am building custom gutenberg blocks using npm, webpack and #wordpress/scripts. Everything was fine until I tried to use block.json file. To use block.json file I need block.asset.php file in the build directory because that's the way WordPress core is coded... (https://github.com/WordPress/gutenberg/issues/40447)
And now my problem is that running npm run build does not generate .asset.php file and I do not know why. When I register blocks using wp_enqueue_script or when I manually create an empty .asset.php it works fine.
My webpack.config.js now looks like this:
const defaultConfig = require("#wordpress/scripts/config/webpack.config");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
...defaultConfig,
entry: {
'cgbms-section-block': './src/section-block.js',
'cgbms-article-block': './src/article-block.js',
'cgbms-article-header-block': './src/article-header-block.js',
'cgbms-category-block': './src/category-block.js',
'cgbms-category-block-edit': './src/category-block-edit.js',
'cgbms-card-block': './src/card-block.js',
'style-front': './src/css/style-front.scss',
'style-editor': './src/css/style-editor.scss',
},
output: {
path: path.join(__dirname, './build/'),
filename: './blocks/[name].js'
},
module: {
...defaultConfig.module,
rules: [
...defaultConfig.module.rules,
]
},
plugins: [
new MiniCssExtractPlugin({
filename: './css/[name].css'
})
],
externals: {
'#wordpress/blocks': 'wp.blocks',
'#wordpress/block-editor': 'wp.blockEditor'
},
}
Okay so solution is actually really simple.
I think I had to import default plugins config:
...defaultConfig.plugins
So my whole webpack.config.js is now:
const defaultConfig = require("#wordpress/scripts/config/webpack.config");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
...defaultConfig,
entry: {
'cgbms-section-block': './src/section-block.js',
'cgbms-article-block': './src/article-block.js',
'cgbms-article-header-block': './src/article-header-block.js',
'cgbms-category-block': './src/category-block.js',
'cgbms-category-block-edit': './src/category-block-edit.js',
'cgbms-card-block': './src/card-block.js',
'style-front': './src/css/style-front.scss',
'style-editor': './src/css/style-editor.scss',
},
output: {
path: path.join(__dirname, './build/'),
filename: './blocks/[name].js'
},
module: {
...defaultConfig.module,
rules: [
...defaultConfig.module.rules,
]
},
plugins: [
...defaultConfig.plugins,
new MiniCssExtractPlugin({
filename: './css/[name].css'
})
]
}
as you can see I also removed externals block.

Javascript plugins do not bundle order wise in webpack

I am trying to bundle my JS files through Webpack (version 5.x) but it is not bundling order-wise. Here is my configuration file:
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "production",
entry: [
"./src/assets/js/plugins/jQuery.js",
"./src/assets/js/plugins/mdb.js",
"./src/assets/js/plugins/aos.js",
"./src/assets/js/main.js",
],
output: {
filename: "assets/js/[name].[contenthash].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
]
};
I am expecting in the bundle file orderwise like jQuery.js, mdb.js, aos.js and main.js that I added in the entry. Please help me find the issue and a better way to buddle the JS files.
Thank You

Lack of javascript error messages with webpack when missing a dependency

I've been recently frustrated when developing using Webpack, because whenever I introuduce a new dependency there are no printed errors if I forget to include the depending JavaScript file(s).
I have created an example project: https://github.com/manstie/test-django-webpack
In the example you can see I have purposely set up the home module to depend on the utils module.
When you run the server and load localhost:8000 it is expected that you get a console log of Here and You have successfully depended on utils.js if you import all the necessary script files.
When utils.js is not included in index.html, base.js does not run at all - it silently fails, with no errors.
I am hoping there is a way to have errors show in the javascript console in these cases? I just can't find any resources or related questions on this issue.
Here is the webpack.common.js config:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const dist = path.resolve(__dirname, 'static/bundles');
module.exports = {
entry: {
utils: './home/js/utils.js',
home: {
import: './home/js/index.js',
dependOn: ['utils']
}
},
resolve: {
modules: ['node_modules']
},
output: {
filename: '[name].[chunkhash].js',
path: dist,
publicPath: 'bundles/',
},
plugins: [
new CleanWebpackPlugin(), // deletes files inside of output path folder
new WebpackManifestPlugin({ fileName: "../../manifest.json" }),
],
optimization: {
moduleIds: 'deterministic', // so that file hashes don't change unexpectedly?
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like # symbols
return `npm.${packageName.replace('#', '')}`;
},
},
},
},
},
};
Here is the html with a missing dependency - I am using django-manifest-loader in order to prevent JavaScript caching issues
...
{% load manifest %}
<script src="{% manifest 'runtime.js' %}"></script>
<!-- Is there a way to have webpack / js tell you about the missing dependency? -->
<!-- <script src="{% manifest 'utils.js' %}"></script> -->
<script src="{% manifest 'home.js' %}"></script>
...
And here are the js files:
index.js
import { testFunc } from "./utils.js";
console.log("Here");
testFunc();
utils.js
export function testFunc()
{
console.log("You have successfully depended on utils.js");
}
Thanks in advance.

Can Webpack build multiple HTML files from SCSS and Pug?

I've read quite a few tutorials on webpack, but it seems more for creating web apps then for what I'm trying to do so I didn't want to waste any more time if the following isn't possible.
I'm creating websites on a third-party eCommerce system and they have a system of coding out templates that can be used to change the structure of their website. Below is an example of one of their templates I would be creating (although there are many types & variations I will need to make, not just a few).
My idea to streamline the creation of these templates is to create a bunch of pug components and place them in the components/ directory. Outside of the components directory I want to make higher level pug templates that utilize the components. Once these have been created, I would build it with NPM and the template files need to be converted to HTML and placed within the /dist folder.
Is this hard to do with webpack?
Structure of the project:
src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss
and once built:
dist/
..navcustom-template.html
..customfooter-template.html
..non-template-specific.css
src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss
Sample of a template:
<!--
Section: NavCustom
-->
<style>
//Template Speific CSS Imports Here
</style>
<script type="text/javascript">
//Template Speific JS Imports Here
</script>
<header>
<div class="col-md-4">
// Social Media Code
</div>
<div class="col-md-4">
// Logo Code
</div>
<div class="col-md-4">
// Call to Action Code
</div>
</header>
<nav>
</nav>
You can use these packages (--save-dev for all):
raw-loader to load the Pug files
pug-html-loader to read the Pug files
html-webpack-pug-plugin to generate HTML from Pug
html-webpack-plugin (standard HTML plugin loader)
Then configure Webpack similar to the following, where index.js is a dummy file you should create if you don't already have an entry. Each Pug template you need to process is written in a separate HtmlWebpackPlugin object at the bottom.
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname + '/dist',
publicPath: '/'
},
module: {
rules: [
{
test: /\.pug$/,
use: [
"raw-loader",
"pug-html-loader"
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/navcustom-template.pug',
filename: 'navcustom-template.html'
}),
new HtmlWebpackPlugin({
template: 'src/customfooter-template.pug',
filename: 'customfooter-template.html'
}),
new HtmlWebpackPugPlugin()
]
}
All Pug mixins (your src/components files) will be included in the output. This example is tested and working.
Edit: To dynamically process all Pug files in the src directory use this config:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
const fs = require('fs');
let templates = [];
let dir = 'src';
let files = fs.readdirSync(dir);
files.forEach(file => {
if (file.match(/\.pug$/)) {
let filename = file.substring(0, file.length - 4);
templates.push(
new HtmlWebpackPlugin({
template: dir + '/' + filename + '.pug',
filename: filename + '.html'
})
);
}
});
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname + '/dist',
publicPath: '/'
},
module: {
rules: [
{
test: /\.pug$/,
use: [
"raw-loader",
"pug-html-loader"
]
}
]
},
plugins: [
...templates,
new HtmlWebpackPugPlugin()
]
}
This uses fs.readdirSync to get all Pug files in a directory. The synchronous version is used (as opposed to fs.readdir) because the module.exports function will return before the files are processed.
in 2022 is appeared the Pug plugin for Webpack that compiles Pug to static HTML, extracts CSS and JS from their source files defined directly in Pug.
It is enough to install the pug-plugin only:
npm install pug-plugin --save-dev
webpack.config.js
const path = require('path');
const PugPlugin = require('pug-plugin');
module.exports = {
output: {
path: path.join(__dirname, 'dist/'),
filename: 'assets/js/[name].[contenthash:8].js'
},
entry: {
// Note: a Pug file is the entry-point for all scripts and styles.
// All scripts and styles must be specified in Pug.
// Define Pug files in entry:
index: './src/views/index.pug', // => dist/index.html
'navcustom-template': './src/navcustom-template.pug', // => dist/navcustom-template.html
'customfooter-template': './src/customfooter-template.pug', // => dist/customfooter-template
// etc ...
},
plugins: [
// enable using Pug files as entry-point
new PugPlugin({
extractCss: {
filename: 'assets/css/[name].[contenthash:8].css' // output filename of CSS files
},
})
],
module: {
rules: [
{
test: /\.pug$/,
loader: PugPlugin.loader, // the Pug loader
},
{
test: /\.(css|sass|scss)$/,
use: ['css-loader', 'sass-loader']
},
],
},
};
Of cause, the entry can be dynamically generated like in the answer above.
In your Pug file use the source files of styles and scripts via require():
html
head
//- add source SCSS styles using a path relative to Pug file
link(href=require('./styles.scss') rel='stylesheet')
body
h1 Hello Pug!
//- add source JS/TS scripts
script(src=require('./main.js'))
Generated HTML:
<html>
<head>
<link href="/assets/css/styles.f57966f4.css" rel="stylesheet">
</head>
<body>
<h1>Hello Pug!</h1>
<script src="/assets/js/main.b855d8f4.js"></script>
</body>
</html>
Just one Pug plugin replaces the functionality of many plugins and loaders used with Pug:
pug-html-loader
html-webpack-pug-plugin
html-webpack-plugin
mini-css-extract-plugin
resolve-url-loader
svg-url-loader
posthtml-inline-svg

require not defined error on bundled JS reactjs

I'm new to Django and ReactJS, was trying to compile a simple JSX code to JS using this tutorial : http://geezhawk.github.io/2016/02/02/using-react-with-django-rest-framework.html
Didn't work, so I used npm run dev to compile, now it worked but giving error in browser console : Uncaught ReferenceError: react is not defined
Here is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var nodeExternals = require('webpack-node-externals');
module.exports = {
//the base directory (absolute path) for resolving the entry option
context: __dirname,
//the entry point we created earlier. Note that './' means
//your current directory. You don't have to specify the extension now,
//because you will specify extensions later in the `resolve` section
entry: './assets/js/index',
output: {
//where you want your compiled bundle to be stored
path: path.resolve('./assets/bundles/'),
//naming convention webpack should use for your files
filename: '[name]-[hash].js',
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: {
react: 'react'
}, // in order to ignore all modules in node_modules folder
plugins: [
//tells webpack where to store data about your bundles.
new BundleTracker({filename: './webpack-stats.json'}),
//makes jQuery available in every module
new webpack.ProvidePlugin({
//React: "react",
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
module: {
loaders: [
//a regexp that tells webpack use the following loaders on all
//.js and .jsx files
{test: /\.jsx?$/,
//we definitely don't want babel to transpile all the files in
//node_modules. That would take a long time.
/*exclude: /node_modules/,*/
//use the babel loader
loader: 'babel-loader',
query: {
//specify that we will be dealing with React code
presets: ['react']
}
}
]
},
resolve: {
//tells webpack where to look for modules
modulesDirectories: ['node_modules'],
//extensions that should be used to resolve modules
extensions: ['', '.js', '.jsx']
}
}
And assets/bundles/index.js
var React = require('react')
var ReactDOM = require('react-dom')
//snaha//
var BooksList = React.createClass({
loadBooksFromServer: function(){
console.log(123454657);
$.ajax({
url: this.props.url,
datatype: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
})
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadBooksFromServer();
setInterval(this.loadBooksFromServer,
this.props.pollInterval)
},
render: function() {
if (this.state.data) {
console.log('DATA!')
var bookNodes = this.state.data.map(function(book){
return <li> {book.title} </li>
})
}
return (
<div>
<h1>Hello React!</h1>
<ul>
{bookNodes}
</ul>
</div>
)
}
})
ReactDOM.render(<BooksList url='/api/' pollInterval={1000} />,
document.getElementById('container'))
And templates/body.html
{% load render_bundle from webpack_loader %}
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<meta charset="UTF-8">
<title>Hello React
{% block content %}
{{ id }}
{% endblock %}
</title>
</head>
<body>
<div id="container"></div>
{% render_bundle 'main' %}
</body>
</html>
Anything I'm missing? here is my Django project structure
Finally I've solved it!
Problem was : it was trying to get variable react where as React.js on browser was providing variable React!
So I simple change of externals of webpack.config.js to
externals: {
React: 'react'
},
solved the issue!
Next Problem Faced :
"process was not defined"
Solution : added
var env = process.env.WEBPACK_ENV;
to top of webpack.config.js
and
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
into the plugins part of model.export
So Final webpack.config.js would be :
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var nodeExternals = require('webpack-node-externals');
var env = process.env.WEBPACK_ENV;
module.exports = {
//the base directory (absolute path) for resolving the entry option
context: __dirname,
//the entry point we created earlier. Note that './' means
//your current directory. You don't have to specify the extension now,
//because you will specify extensions later in the `resolve` section
entry: './assets/js/index',
output: {
//where you want your compiled bundle to be stored
path: path.resolve('./assets/bundles/'),
//naming convention webpack should use for your files
filename: '[name]-[hash].js',
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: {
React: 'react'
}, // in order to ignore all modules in node_modules folder
plugins: [
//tells webpack where to store data about your bundles.
new BundleTracker({filename: './webpack-stats.json'}),
//makes jQuery available in every module
new webpack.ProvidePlugin({
//React: "react",
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
],
module: {
loaders: [
//a regexp that tells webpack use the following loaders on all
//.js and .jsx files
{test: /\.jsx?$/,
//we definitely don't want babel to transpile all the files in
//node_modules. That would take a long time.
/*exclude: /node_modules/,*/
//use the babel loader
loader: 'babel-loader',
query: {
//specify that we will be dealing with React code
presets: ['react']
}
}
]
},
resolve: {
//tells webpack where to look for modules
modulesDirectories: ['node_modules'],
//extensions that should be used to resolve modules
extensions: ['', '.js', '.jsx']
}
}
Now Enjoy React! Happy Coding :-)
Can you look if you have all the requirements installed.
Look inside package.json. You should have react noted in requirements if you do run.
npm install
If you don't, then run
npm install react --save
ps: in my option if you are running Webpack try to add babel to Webpack presets and write javascript in ES2015 specification.

Categories