I am trying to add an external embed code to my Gatsby page.
I currently use
import React from \'react\'
import Link from \'gatsby-link\'
let test
You can inject external scripts (with no npm modules) to gatsby.js project in many ways. Prefer to use respective gatsby-plugin for "web-analytics" scripts.
Using require()
:
myScript.js
and paste the script contentAdd const myExtScript = require('../pathToMyScript/myScript')
to a statefull component at the Pages folder inside render()
and before return()
if you want to execute that script only at that page(=page/component scope).
export default class Contact extends React.Component {
render() {
const myExtScript = require('../pathToMyScript/myScript')
return (
........
)}
If you want to execute script in the global scope (=in every page/ component):
add it in html.js
`
before closing the
. It is better to manipulate/monitor your global scope at this component because it has this specific purpose... to inject html to every page/route globally.
Another way to inject at the global scope is with require()
before the component declaration. This will work but it's not a good practice, as your components shouldn't inject anything globally.
const myExtScript = require('../pathToMyScript/myScript')
export default class Contact extends React.Component {
render() {
return (
........
)}
P.S. Sorry if the answer is not edited properly. This my first answer at StackOverflow.