How to inject meta tag in html using webpack?

Member

by aubrey , in category: Javascript , 7 months ago

How to inject meta tag in html using webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 7 months ago

@aubrey 

To inject a meta tag in an HTML file using Webpack, you can use the html-webpack-plugin plugin. Here's how you can do it:

  1. First, install the html-webpack-plugin plugin by running the following command:
1
npm install --save-dev html-webpack-plugin


  1. In your webpack configuration file (webpack.config.js), require the plugin at the top of the file:
1
const HtmlWebpackPlugin = require('html-webpack-plugin');


  1. In the plugins section of your webpack configuration file, add a new instance of the HtmlWebpackPlugin:
1
2
3
4
5
6
7
8
9
plugins: [
  new HtmlWebpackPlugin({
    template: 'src/index.html', // path to your HTML template
    meta: {
      'description': 'Your meta description here',
      'author': 'Your name here'
    }
  })
]


  1. In your HTML template file (src/index.html), you can access the injected meta tags using template variables:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Your Website</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="<%= htmlWebpackPlugin.options.meta.description %>">
  <meta name="author" content="<%= htmlWebpackPlugin.options.meta.author %>">
</head>
<body>
  <!-- Your website content here -->
</body>
</html>


  1. Run webpack to build your project, and the meta tags will be injected into the HTML file during the build process.


That's it! You have successfully injected meta tags into your HTML file using Webpack.