Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
how do you add external javascript in Next.js?

I'm learning Next.js and have spent hours trying to add external javascript.

I want to load this external script I named query.js into /pages/index.js

console.log("script loaded!")
function hello(){
    console.log("hello!")
}

The script does load when I imported the script on _app.js

import '../styles/globals.css'
import '../public/static/query.js'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

but calling the function like this on index.js returned "ReferenceError: hello is not defined" even though the script already loaded.

export default function Home() {
  return (
  /* some div */
  {hello()}
  /* the rest of the code */
  )

what did I do wrong? I want the script to do some data processing on the browser. I have tried

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

it totally depends on how you plan to import your JS file.

Your current approach

your current approach is creating a side effect only module which your import statement initializes- that is why you see the console.log statement. to make this work just attach hello function to the window object which is not recommended.

Recommended approach

Usually, it's best to create modules without side effects. in that case to make this work you should export your function and import it in whatever module that you need. here's an example:

console.log("script loaded!")
export function hello(){
    console.log("hello!")
}

and in your module

import {hello} from 'wherever';

export default function Home() {
  return (
  /* some div */
  {hello()}
  /* the rest of the code */
)
about 4 years ago · Juan Pablo Isaza Relatório

0

To add external javascript in Next.js you can use the Script component from next/script since v11.0.0.

Example from their website:

import Script from 'next/script'

export default function Home() {
  return (
    <>
      <Script src="https://www.google-analytics.com/analytics.js" />
    </>
  )
}

More info in their official docs.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda