In official doc says when applying Code Splitting and generating chunk files, if chunk code changes, then the filename of it will change. However index.html which uses the chunk code files can't change the filename in its <script> tag, so in this case the manifest.json which is generated by webpack-manifest-plugin will help mapping [name].js to [name].[hash].js.
But opposing to what the doc says, it seems that every time I run webpack to build my codes, new codes are generated with new hash value in its file(in case something in code changed), and HTML-Webpack-Plugin will autometically inject <script> tag with new name of code's file. This seems that there is no need to use webpack-manifest-plugin, I don't even see where the manifest.json is used.
In case if you are looking for my webpack.config.js:
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
module.exports = {
entry: ["core-js/stable", "regenerator-runtime/runtime", "./src/index.jsx"],
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(`${__dirname}/build`)
},
mode: "none",
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: "/node_modules",
use: ['babel-loader']
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
template: './public/index.html'
}),
new ManifestPlugin({
fileName: 'manifest.json'
})
// need this plugin for SSR?
]
}
What is the detailed usage of webpack-manifest-plugin and manifest.json?
HtmlWebpackPlugin "knows" that your asset bundle.js maps to bundle.some-hash.js because it uses the Webpack's Manifest. This manifest is not emitted though. It's just data that Webpack uses to keep track of how all the modules map to the output bundles.
WebpackManifestPlugin uses Webpack's manifest data data to emit a JSON file (that you can call manifest.json or whatever you want).
Since you are using HtmlWebpackPlugin with the inject: true option (it's the default one), HtmlWebpackPlugin injects your bundle bundle.some-hash.js into your template. So you probably have no need to use WebpackManifestPlugin for your application.
If you did not use HtmlWebpackPlugin, or if you used it with inject: false, then you would need to find a way to "manually" inject the assets generated by Webpack.
So, the manifest.json is not for Webpack. It's for you.
Let's say for example that you have a Python Flask web application and your web pages are built with Jinja templates. You could use Webpack to generate all of your static assets, and use the manifest.json to resolve the asset generated by Webpack. This Flask extension does just that. This means that in your jinja template you can write this:
<img src="{{ asset_for('images/hamburger.svg') }}" alt="Hamburger">
and get this:
<img src="images/hamburger.d2cb0dda3e8313b990e8dcf5e25d2d0f.svg" alt="Hamburger">
Another use case would be if you want fine control where the bundles are injected into your templates. For that, have a look at this example in the html-webpack-plugin repo.
Related
I'm developing a Chrome Extension and I use Webpack to bundle it. I've got my compiled bundle, which is the main part of the app, but I also need an options page to describe the functionality. This options page has nothing to do with the bundle, it's just a static HTML file.
I must put a lot of things in that options page so I want to render that page with Mustache and define all content with JavaScript. For the most part, I've done that.
Here's my Webpack config (I've removed the parts regarding my app):
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
output: {
path: path.join(__dirname, 'extension/build/')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/options/index.html',
inject: false
})
],
module: {
rules: [
{
test: /\.html$/,
loader: 'mustache-loader',
options: {
render: require('./src/options/index.js')
}
}
]
}
}
and in my src/index.js, I have:
require('./options/index.html')
This will open the template and render it with the data in src/options/index.js.
There's a problem with that, however. I run Webpack with webpack --watch and changes to index.js (it holds the template data) do not trigger a rebuild. Also, I would need to go through a lot of trouble to create another static HTML file in the same manner.
It would be ideal if HtmlWebpackPlugin automatically used the template I require() in my entry point so that I don't need to explicitly set it. Also, it would be great if it automatically used a js in that same location to get the data. For example:
require('./options/index.html`)
Renders the template with data from ./options/index.html.js and then emits it. It would be even better if it emitted it to a custom folder specified in the Webpack config.
Is that possible? I couldn't find a plugin/loader that does that.
Edit: I was able to partly fix the rebuild problem by specifying the render option as a function:
{
test: /\.html$/,
loader: 'mustache-loader',
options: {
render () {
var file = './src/options/index.js'
delete require.cache[require.resolve(file)]
return require(file)
}
}
}
But it still doesn't work properly. The rebuild would only trigger after I make changes to index.html. This means that if I change index.js, I need to go and save index.html as well to trigger the build.
In another question, an accepted answer with 11 upvotes suggests using webpack's html-webpack-plugin to merge HTML+JS+CSS.
Not a single word on how though, so that's my question. I have a documentation file, in HTML. It includes two external CSS files and one javascript file (syntax highlighter). I would like to bundle it all into one HTML file for easy distribution.
I tried to use webpack without packing any JS with following webpack.config.js:
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
plugins: [
new HtmlWebpackPlugin({
title: 'Documentation',
template: "index.html",
filename: 'index_bundle.html'
})
]
};
But that caused an error because webpack requires input and output script path:
Error: 'output.filename' is required, either in config file or as --output-filename
So how do I do this. Is webpack even the right choice?
What's tricky here is that webpack and HtmlWebpackPlugin each have their own entry-output pipeline. You don't care about webpack's entry point and output; you care about HtmlWebpackPlugin's, but in order for HtmlWebpackPlugin to run at all, you have to let webpack do its thing.
There's a clever trick that I stole from https://stackoverflow.com/a/43556756/152891 that you could do here -- tell webpack to output its bundle at index.html, and then tell HtmlWebpackPlugin to output to the same location. Webpack will run first, and then HtmlWebpackPlugin will overwrite its output. You still need to define an entry point for webpack, but this can be a blank index.js.
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'none',
entry: './src/index.js', // Default value, can omit
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html', // Default value, can omit
inject: false,
minify: false
})
],
output: {
filename: "index.html",
path: path.resolve(__dirname, 'dist')
}
};
You can either keep a blank ./src/index.js file in your repo, or you could define a little inline plugin in your webpack.config.js to create the file on run, and add it to your .gitignore.
plugins: [
{
apply: (compiler) => {
compiler.hooks.beforeRun.tap('NoOpPlugin', () => {
fs.writeFileSync('./src/index.js');
});
}
}
]
I am using HTMLWebpackPlugin and in my template I have an img tag:
<img src="./images/logo/png">
If you notice, here I am using a relative path thinking webpack will trigger the file loader that's configured in my webpack.config.js file but after compilation I get the exact same src attribute in my html:
<img src="./images/logo/png">
How can I trigger webpack to dynamically replace these relative paths with, well whatever I've configured in my webpack configuration?
I'm not a webpack expert, but i got it to work by doing this:
<img src="<%=require('./src/assets/logo.png')%>">
Plugin config
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html'
}),
According to the docs: https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md
By default (if you don't specify any loader in any way) a fallback
lodash loader kicks in.
The <%= %> signifies a lodash template
Under the hood it is using a webpack child compilation which inherits
all loaders from your main configuration.
Calling require on your img path will then call the file loader.
You may run into some path issues, but it should work.
Using html-loader with HTML webpack plugin worked for me.
module: {
rules: [
{
test: /\.(html)$/,
use: ['html-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
You should use the CopyWebpackPlugin.
const CopyWebpackPlugin = require('copy-webpack-plugin');
plugins:[
....
new CopyWebpackPlugin({'patterns': [
{from:'./src/assets/images', to:'images'}
]}),
....
]
This is copy the src/assets/images to your `distfolder/images'.
You could use url-loader in your webpack config to add images below a certain limit encoded as base64 uri's in your final bundle and images above the limit as regular image tags (relative to the publicPath)
module.rules.push({
test: /\.(png|jp(e*)g|gif)$/,
exclude: /node_modules/,
use: [{
loader: 'url-loader',
options: {
limit: 10000,
publicPath: "/"
}
}]
})
I ran into this issue while following the Getting Started guide that Webpack provides. I was using the template code from the guide and bundling images. But then when migrating an existing vanilla html/js/css project to use Webpack, I discovered that in order to use the template HTML loading like I wanted -- with paths to image resource contained in the template -- I had to remove the asset loader usage from my webpack.config.js for the html-loader to properly resolve the new hashed paths it was creating in dist
To use Webpack doc syntax, remove the lines prefixed with "-" and add the lines prefixed with "+"
module: {
rules: [
{
- test: /\.(png|svg|jpg|jpeg|gif)$/i,
- type: 'asset/resource',
+ test: /\.(html)$/,
+ use: ['html-loader'],
}
]
}
I'm learning React and want to understand how web pack is configured for a project.
It would be great if someone can tell me what the following lines of code are doing.
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
function isDirectory(dir) {
return fs.lstatSync(dir).isDirectory()
}
const SubjectsDir = path.join(__dirname, 'subjects')
const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
return isDirectory(path.join(SubjectsDir, dir))
})
module.exports = {
devtool: 'source-map',
entry: SubjectDirs.reduce(function (entries, dir) {
if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')
return entries
}, {
shared: [ 'react', 'react-dom' ]
}),
output: {
path: '__build__',
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: '__build__'
},
resolve: {
extensions: [ '', '.js', '.css' ]
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.js$/, exclude: /node_modules|mocha-browser\.js/, loader: 'babel' },
{ test: /\.woff(2)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
{ test: /\.ttf$/, loader: 'file' },
{ test: /\.eot$/, loader: 'file' },
{ test: /\.svg$/, loader: 'file' },
{ test: require.resolve('jquery'), loader: 'expose?jQuery' }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'shared' })
],
devServer: {
quiet: false,
noInfo: false,
historyApiFallback: {
rewrites: [
{ from: /ReduxDataFlow\/exercise.html/,
to: 'ReduxDataFlow\/exercise.html'
}
]
},
stats: {
// Config for minimal console.log mess.
assets: true,
colors: true,
version: true,
hash: true,
timings: true,
chunks: false,
chunkModules: false
}
}
}
This informaiton is coming from a training course, but they do not explain what the lines are doing.
Webpack is what we call a module bundler for JavaScript applications. You can do a whole slew of things with it that help a client browser download and run your code. In the case of React, it helps convert JSX code into plain JS so that the browser can understand it. JSX itself will not run in the browser. We can even use plugins to help minify code, inject HTML, bundle various groups of code together, etc. Now that the introduction to Webpack is out of the way, let's take a look at the code. I will be starting from the very top. Feel free to skip down to #3 if you are only interested in the Webpack configuration object.
The following code will require the modules that are needed in this file. fs is short for "filesystem" and is a module that gives you functions to run that can access the project's filesystem. path is a common module used to resolve or create pathnames to files and is very easy to use! And then we have the webpack module through which we can access webpack specific functions (ie: webpack plugins like webpack.optimize.UglifyJsPlugin).
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
These next few lines first set up a helper function to determine whether or not something in the filesystem being read is a directory.
function isDirectory(dir) {
return fs.lstatSync(dir).isDirectory()
}
const SubjectsDir = path.join(__dirname, 'subjects')
const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
return isDirectory(path.join(SubjectsDir, dir))
})
devtool specifies which developer tool you want to use to help with debugging. Options are listed here : https://webpack.github.io/docs/configuration.html#devtool. This can be very useful in helping you determine exactly which files and lines and columns errors are coming from.
devtool: 'source-map'
These next few lines tell Webpack where to begin bundling your files. These initial files are called entry points. The entry property in a Webpack configuration object should be an object whose keys determine the name of a bundle and values point to a relative path to the entry file or the name of a node_module. You can also pass in an array of files to each entry point. This will cause each of those files to be bundled together into one file under the name specified by the key - ie: react and react-dom will each be parsed and have their outputs bundled under the name shared.
entry: SubjectDirs.reduce(function (entries, dir) {
if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')
if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')
return entries
}, {
shared: [ 'react', 'react-dom' ]
}),
In the reduce function we simply read through the SubjectsDir, determine whether files exercise.js, lecture.js & solution.js exist, and then provide the path to those files as values associated with the key names identified by dir + '-' + filename (ie: myDir-exercise). This may end up looking like the following if only exercise.js exists:
entry : {
'myDir-exercise': 'subjectDir/myDir/exercise.js',
share: ['react', 'react-dom']
}
After we provide entry points to the Webpack configuration object, we must specify where we want Webpack to output the result of bundling those files. This can be specified in the output property.
output: {
path: '__build__',
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: '__build__'
},
The path property defines the absolute path to the output directory. In this case we call it __build__.
The filename property defines the output name of each entry point file. Webpack understands that by specifying '[name]' you are referring to the key you assigned to each entry point in the entry property (ie: shared or myDir-exercise).
The chunkFilename property is similar to the filename property but for non-entry chunk files which can be specified by the CommonChunksPlugin (see below). The use of [id] is similar to the use of [name].
The publicPath property defines the public URL to where your files are located, as in the URL from which to access your files through a browser.
The resolve property tells Webpack what how to resolve your files if it can not find them for some reason. There are several properties we can pass here with extensions being one of them. The extensions property tells Webpack which file extensions to try on a file if one is not specified in your code.
resolve: {
extensions: [ '', '.js', '.css' ]
},
For example, let's say we have the following code
const exercise = require('./exercise');
We can leave out the .js because we have provided that string in the resolve property of the webpack configuration and Webpack will try and append .js to this at bundling time to find your file. As of Webpack 2 we also no longer need to specify an empty string as the first element of the resolve property.
The module property tells Webpack how modules within our project will be treated. There are several properties we can add here and I suggest taking a look at the documentation for more details. loaders is a common property to use and with that we can tell Webpack how to parse particular file types within our project. The test property in each loader is simply a Regex that tells Webpack which files to run this loader on. This /\.js$/ for example will run the specified loader on files that end with .js. babel-loader is a widely used JavaScript + ES6 loader. The exclude property tells Webpack which files to not run with the specified loader. The loader property is the name of the loader. As of Webpack 2 we are no longer able to drop the -loader from the string as we see here.
Plugins have a wide range of functions. As mentioned earlier we can use plugins to help minify code or to build chunks that are used across our entire application, like react and react-dom. Here we see the CommonChunksPlugin being used which will bundle the files under the entry name shared together as a chunk so that they can be separated from the rest of the application.
Finally we have the devServer property which specifies certain configurations for the behavior of webpack-dev-server, which is a separate module from webpack. This module can be useful for development in that you can opt out of building your own web server and allow webpack-dev-server to serve your static files. It also does not write the outputs to your filesystem and serves the bundle from a location in memory at the path specified by the publicPath property in the output property of the Webpack configuration object (see #5). This helps make development faster. To use it you would simply run webpack-dev-server in place of webpack. Take a look at the documentation online for more details.
The configuration object that we've taken a look at follows the Webpack 1 standard. There are many changes between Webpack 1 and 2 in terms of configuration syntax that would be important to take a look at. The concepts are still the same, however. Take a look at the documentation for information on migrating to Webpack 2 and for further Webpack 2 details.
I'm trying out the multi-compiler option in webpack and am following the example at their github. However, I can't seem to understand how I can split out the common code amongst the multiple configurations.
For example, I may have same vendor libraries used in the different set of configurations. I would like to have these shared codes to be bundled to one single common file.
I tried the following but it ended up creating an individual bundles of the vendors entry for each compile configuration.
var path = require("path");
var webpack = require("webpack");
module.exports = [
{
name: "app-mod1",
entry: {
vendors: ['jquery', 'react', 'react-dom'],
pageA: ['./mod1/pageA'],
pageB: ['./mod1/pageB']
},
output: {
path: path.join(__dirname, "/mod1/js"),
filename: "[name].bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendors'],
minChunks: Infinity
})
]
},
{
name: "app-mod2",
entry: {
vendors: ['lodash', 'react', 'react-dom'],
pageA: ['./mod2/pageA'],
pageB: ['./mod2/pageB']
},
output: {
path: path.join(__dirname, "/mod2/js"),
filename: "[name].bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendors'],
minChunks: Infinity
})
]
}
];
Since react, react-dom are shared between the 2 compilations, my intention is for them to be bundled as a single file which can be shared instead of creating a same bundle for each compilation.
How can I extract the common chunks out of multiple compiler configurations?
Brief answer
You can't do that job in the way you want.
TL;DR
#Carven, I am afraid that you can't achieve your goal via MultiCompiler of Webpack, MultiCompiler is not meant to do that job, at least for the near feature.
See the source code for initiating the MultiCompiler instance, it actually initiates separate Compiler instances. These compiler have no data shared between.
See also the source of running MultiCompiler instance, the compilers instance also run separately without sharing data.
The only thing these compilers share is the Stats instance they produce and merge into a MultiStats.
By the way, there is no clue in the example you mentioned that some modules are shared between multi-compilers.
Alternative
As described by #Tzook-Bar-Noy, IMHO, you have to use muti-entries to achieve MPA(Multi-page Application) bundling.
Other worth mentioning
I noticed a library called webpack-multi-configurator is using the multi-compiler feature. But I don't think it will share common chunk(s).
You can extract the shared code into another compilation, and bundle it with DllBundlesPlugin.
later consume this DLL via DLLReferencePlugin and add it to your page either manually or via HTMLWebpackPlugin's add-asset-html-webpack-plugin
Bolierplate can be reduced by using autodll-webpack-Plugin
I learned about it now, and this topic seems quite hard to understand in webpack docs. I managed to create something that works, as it created 2 separate files and extracted the common dependencies to another file.
Here is my webpack config:
{
entry: {
pageA: "./first/first",
pageB: "./second/second"
},
output: {
path: path.join(__dirname, "js"),
filename: "[name].js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ["vendor", "common"],
})
]
};
the output of this will be:
./js/
common.js
vendor.js
pageA.js
pageB.js
I created a repo with the example I worked on: https://github.com/tzookb/webpack-common-vendor-chunks
when I open a new html file I load these files:
first page:
common.js
vendor.js
pageA.js
sec page:
common.js
vendor.js
pageB.js