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]}`} />