Getting Started
Utilize meta-generator
to populate document metadata in a React application. Generate meta tags for Open Graph and Twitter along with other useful metadata. All of the tags necessary for baseline social share functionality are included with this utility along with additional tags for more custom use cases.
What you'll need
- A React project
- JavaScript Environment
Setup
In your project, install the plugin from npm:
npm install meta-generator
Usage
Use a prebuild script such as replace-head.js
paired with meta-generator
to populate the <head>
of your public/index.html
file.
const fs = require('fs');
const metagen = require('meta-generator');
const boilerplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<!-- {% metagen %} -->
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>`;
const head = metagen({
title: 'Book.js',
desc: 'Reusable 3D Book Component with GSAP animation',
url: 'https://extraordinary-kheer-4bd56b.netlify.app',
img: 'https://user-images.githubusercontent.com/48612525/273147153-54f1c51c-120a-487f-a023-d1394354ddd5.png',
img_alt: 'Demo image of book component displaying Hitchiker\' Guide to the Galaxy',
twitter_card_type: 'summary_large_image',
twitter_handle: 'tannerdolby',
name: 'Tanner Dolby',
comments: true,
}).join('\n');
const content = boilerplate.replace('<!-- {% metagen %} -->', head);
fs.writeFile('./public/index.html', (content.trim()), (err) => {
if (err) throw err;
});
Then update package.json:
"scripts": {
"prebuild": "node <path-to-replace-head-script>",
"build": "react-scripts build",
},
Now when you npm run build
, the prebuild script will run and replace the <!-- {% metagen %} -->
with document metadata generated by the meta-generator
.
Examples
See react-book for an example of meta-generator
in action. Alernatively, you could try using something like react-helmet-async
paired with meta-generator
.
React frameworks like Next.js provide a much more robust way to define document metadata through their Metadata API. I highly recommended using that for your Next.js project unless you can find a use case for meta-generator
that works for you.