Adding custom script bundles in NextJS is a great way to enhance the functionality and

I am facing a challenge with incorporating legacy custom JavaScript files into my project. These scripts need to be bundled and linked in the _document.js file with a hash included in the filename.

What is the most effective approach to achieve this?

I have attempted various webpack configurations for entry/output, but they interfere with the NextJs build process.

The issue arises from our usage of objects like window, document, etc., which cause problems on the server-side.

The ideal solution would be to inject the compiled/babelified JavaScript code within a script tag.

Here are some methods I've tried:

  • Utilizing Webpack HTML Plugin along with other plugins such as InlineChunk or InlineSource. Unfortunately, these did not work as they generate code in an index.html that is not utilized by NextJS.

  • Trying to extract the file content using Raw Loader. This method fails as the content is not babelified.

  • Including a custom entry in the Webpack config under scripts: 'path/to/my-entry.js'. This approach failed because it appends a hash name to the file without providing visibility on what the hash actually is.

  • Adding a custom entry to the NextJs polyfills. While this seemed logical, the polyfill tag contains a nomodule attribute that prevents its code from running on newer browsers.

  • An alternative option is to add the JavaScript code as a string and then use __dangerouslySetInnerHtml. However, this poses limitations on linting and Babel abilities.

  • Attempting to include the JavaScript as a separate page resulted in crashes during local development and builds.

webpack.config.js

module.exports = (nextConfig = {}) =>
  Object.assign({}, nextConfig, {
    webpack(config, options) {
      const nextJsEntries = config.entry;
      config.entry = async () => {
        const entries = await nextJsEntries();
        entries['pages/rscripts'] = 'test/test.js';
        return entries;
      };
   ...

Following this, in _document.js

<script src={`${publicRuntimeConfig.ASSET_PREFIX}/_next/${this.props.buildManifest.pages['/rscripts'][2]}`} />

Answer №1

To import a JavaScript file, simply use the code import 'path/to/js_file' in your _app.js or app.tsx file

import "../styles/globals.css"
import "../js/test"

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

export default MyApp

This method has been effective for me.

Answer №2

While browsing the latest updates in Next JS, I stumbled upon something interesting that I wanted to share with you all. It appears that there have been some changes in Next JS recently. One notable addition is the introduction of the script component, allowing users to easily load external scripts or set a script in a risky manner.

The new Next.js Script component, known as next/script, serves as an extension of the HTML element. It grants developers the ability to specify the load priority of third-party scripts at any point in their application, beyond next/head. This not only saves developers time but also enhances loading performance.

What's fascinating is that you can place these scripts on specific pages as per your requirement. For instance, if you want a script to run only on the homepage and not on other pages, Next will handle this for you based on the chosen strategy. However, it's crucial to note a few caveats such as the inability to load in the head section and the somewhat finicky behavior of beforeInteractive. It's advisable to read through the provided links above and consult the actual API reference before making any decisions.

import { useEffect } from 'react';
import Script from 'next/script';

function thirdPartyScript() {
  useEffect(() => {
    // Just for demonstration purposes. This function actually runs
    // before the onLoad callback
  }, []);
  return (
    <Script
      id="test-script"
      strategy="afterInteractive"
      src="/public/pages/scripts/test.js"
      onLoad={() => {
        console.log('The Onload event triggers as expected');
      }}
    />
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement tooltip functionality in ssr chart using echarts

A chart is generated using echarts on the server-side: getChart.ts const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 400, height: 300 }); chart.setOption({ xAxis: { data: timeData }, ...

Webpack and terser reveal the names of the source files in the compressed output

Is there a way to stop source filenames from appearing in webpack output even when using Terser for minification? Illustration After minifying my production React app build, the resulting .js output file still contains original source filenames rather th ...

The website doesn't give my codes enough time to execute fully

I have a series of commands that I need to execute: Retrieve cookie from the browser using the JS Cookie plugin in mypage.php Validate its value with Ajax and my PHP scripts in myapi.php Set certain SESSION variables in myapi.php Utilize the values store ...

A technique for postponing the addition of a class to a div

I am attempting to create a unique type of slider effect. Inside a single div named #slider, I have 9 items displayed in a line. Link to JsFiddle The slider is 1860px wide, but only 620px is visible at any given time due to the parent having an overflow: ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...

Safari showing white flash upon setting background-image src using Intersection Observer?

I've done extensive research but I'm still struggling to solve this issue. It only seems to be happening on Safari (Mac & iOS), while everything works smoothly on Chrome, Firefox, Edge, and other browsers. UPDATE: The flickering problem also per ...

I am curious about the types of props for the methods within the 'components' object in react-markdown

Having some trouble using 'react-markdown' in NextJs 13 with typescript. TypeScript is showing errors related to the props of the 'code' method, and after searching online, I found a solution that involves importing 'CodeProps&apos ...

Shadows and reflections are not supported on Threejs PlaneGeometry

I'm relatively new to the world of 3D graphics and three.js, and I'm struggling to figure out how to achieve individually illuminated polygons on a PlaneGeometry. I've been working on applying some noise to the vertices' z-values in ord ...

How can we incorporate Django template tags into our jQuery/JavaScript code?

Is it possible to incorporate Django's template tags within JavaScript code? For example, utilizing {% form.as_p %} in jQuery to dynamically inject forms onto the webpage. ...

How do I define the specific icon to display on the splash screen for progressive web apps?

In my Progressive Web App (PWA), I have set icons at sizes 144 and 512. Although both icons appear in the application tab in Chrome, the splash screen displays a really small icon (I assume it's using the 144 icon). Is there a method to indicate which ...

Achieving Center Alignment for Material-UI's <Table> within a <div> using ReactJS

Currently, I am working with a Material-UI's <Table> embedded within a <div>. My goal is to center the <Table> while maintaining a fixed width. I want the table to remain centered in the browser, but if the browser window is minimize ...

Can anyone point me to the Angular-2-Release that is located on the https://code.angularjs.org

Word has it that angular 2 has finally made its debut. Personally, I'm not a big fan of relying on npm and bower to automatically load my components. I prefer to keep my dependencies minimal and fully understand each one. Additionally, I like to utili ...

Locate the ancestors of a specific element inside a designated container

Reviewing my code, it contains... <div class="container"> <div id="tropical"> <div class="info"> <div class="desc"> <p>Lorem ipsum.......</p> ...

How can I fix the issue of clearInterval not functioning properly in an Electron JS application?

The clearInterval function is not working properly in this code. What can be done to fix this issue? var inter; ipcMain.on("start-stop",(err,data)=>{ console.log(data.data) function start(){ inter = setInterval(fu ...

Top scenario and illustration of utilizing clusters in nodejs

I've been exploring the concept of clusters and I'm still a bit unclear about the most effective use-case scenario for them. Can anyone provide an example to help clarify this for me? ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...

Tips for adding animation to a React state value change triggered by an input

In my React application, I have a form with multiple fields that each contain a text input and a range input. Currently, both inputs share the same state value and onChange function to keep them synchronized. However, I would like to add an animation effe ...

Japanese Character File Naming Convention

When dealing with certain Japanese characters, the content disposition header appears as follows: Content-Disposition: attachment; filename=CSV_____1-___.csv; filename*=UTF-8''CSV%E3%82%A8%E3%83%93%E3%83%87%E3%83%B3%E3%82%B91-%E3%82%B3%E3%83%94%E ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolo ...