I started with the following code, which is intended to create a multi-select button box using Tailwind and DaisyUI in Next.js (The filename of the problematic code snippet is install.js).
I'm rendering it with webpack by running npx next
, and index.js
works perfectly. However, install.js
is not rendered, and shows a "jQuery requires a window..." error.
import Head from 'next/head'
import React from 'react';
import $ from 'jquery';
export default function Home() {
return (
<div class="flex-1 p-10 w-full max-w-4xl my-2">
(function ($, cmdMap) {
var cmdTxt = $('.command .text');
var opts = {
version: 'stable (recommended)',
pm: 'pip',
gpu: 'YES',
};
function buildMatcher() {
return opts.version.toLowerCase() + ',' + opts.pm.toLowerCase() + ','
+ opts.gpu.toLowerCase()
}
function updateCommand() {
var match = cmdMap[buildMatcher(opts)];
cmdTxt.html(match);
}
function selectOption(ev) {
var el = $(this);
el.siblings().removeClass('btn-active');
el.addClass('btn-active');
opts[el.parents('.option-row').data('key')] = el.text();
updateCommand();
}
$('.option-set').on('click', '.btn', selectOption);
updateCommand();
}(jQuery, {
'stable,conda,no': 'a string',
/* ... */
}))
}
<div class="shadow-lg mockup-code">
<pre><code>{/* TODO: figure out what to put here */}</code></pre>
<pre class="pt-3 link"><code><a href="help">What is this?</a></code></pre>
</div>
<div class="pt-5 btns">
<div class="btn-group">
<button class="btn btn-active">stable (recommended)</button>
<button class="btn">nightly</button>
</div>
<div class="pt-3 btn-group">
<button class="btn btn-active">pip</button>
<button class="btn">docker</button>
<button class="btn">conda</button>
</div>
<div class="pt-3 btn-group">
<button class="btn btn-active">GPU Enabled</button>
<button class="btn">No GPU</button>
</div>
</div>
</div>
)
}
Which yields the following server error: Error: jQuery requires a window with a document
at line 14
| (function ($, cmdMap) {
> | var cmdTxt = $('.command .text');
^
| var opts = {
When I followed the answers here, by adding the following snippet at the specified line numbers:
7 var jsdom = require('jsdom');
8 $ = require('jquery')(new jsdom.JSDOM().window);
I receive an unexpected token error. Sorry if this is silly, I'm really new to JS.
How should I proceed?
Edit: The jQuery function was non-critical for me so I ended up working around it. I still am not too clear on how to resolve this.