I am trying to import static js files using helmet or using Gatsby SSR API.
But using both of them, I always get Uncaught SyntaxError: Unexpected token '<'
.
Maybe I am getting the error because the path is not correct.
Try 1:
src/component/ProductDetail/ProductDetail.js
const ProductDetail = ({ data }) => { return ( <> <Helmet> <script type="application/javascript" src={"./plugins/zaius/index.js"} /> </Helmet> <div css={styles.layout}> ...
Note: zaius plugin js file, the path is static/plugins/zaius/index.js
Try 2:
gatsby-ssr.js
export const onRenderBody = ({ setHeadComponents }) => { setHeadComponents([ <script type="application/javascript" href="./plugins/zaius/index.js" /> ]) }
My Gatsby project architecture is normal, nothing special.
|-- /src |-- /pages |-- /templates |-- html.js |-- /static |-- /plugins |-- /zaius |-- index.js |-- gatsby-config.js |-- gatsby-node.js |-- gatsby-ssr.js |-- gatsby-browser.js
If I compile using npm run dev
, then the structure will be:
|-- /plugins |-- /zaius |-- index.js |-- index.html
I think the reason why I am getting the error Uncaught SyntaxError: Unexpected token '<'
is because the zaius plugin index.js file path is wrong.
Because I tried to clean .cache
using gatsby clean
, and I get the error only when I import the js file.
And please refer to my previous question. here
Answer
I guess that from your ProductDetail
the src
should be:
<Helmet> <script type="application/javascript" src="../../plugins/zaius/index.js" /> </Helmet>
In your gatsby-ssr.js
, this should also work:
export const onRenderBody = ({ setHeadComponents }) => { setHeadComponents([ <script src="./plugins/zaius/index.js" /> ]) }
Note that in this second try, I’ve changed link
to script
tag, since it’s what you are importing (not a stylesheet).
I’ve tested both mocking the plugin and the structure and they are not breaking the compilation.