I have a react, vite project that is in typescript and of “type: module”, however, I need to call a one-of-a-kind file that is built with “require” syntax rather than “import”. I can’t update it so I have to get the two working together and I’ve been unable to.
I’ve built a “wrapper.js” file that contains the following code to try and convert the older format to the import format for use:
const {getProduct, getProducts} = require("../../../server/productInfo");
export {getProduct, getProducts};
But with the above code, I get the error:
ReferenceError: require is not defined
So, following internet solutions I added this at the top of the file:
import { createRequire } from "module"; // "node:module"
const require = createRequire(import.meta.url);
But that give’s me this new error:
SyntaxError: The requested module '/node_modules/.vite/deps/module.js?v=21b36cad' does not provide an export named 'createRequire'
So, then I tried importing module as default, but that seemed to be null
import module from "module";
console.log(module) // null
I then tried to polyfill it like below.
// vite.config.ts
import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import pkg from './package.json' assert { type: 'json' }
import react from '@vitejs/plugin-react-swc'
export default defineConfig({
plugins: [
nodePolyfills(),
react({ plugins: [['@swc/plugin-styled-components', {}]] }),
],
define: {
APP_VERSION: `"${pkg.version}"`,
APP_TITLE: `"${pkg.displayName}"`
},
build: {
outDir: '../server/frontend/dist',
},
})
But I’m unsure how to use it. Because if I do the below, I still get a “require is not defined” error.
import { createRequire } from "module";
const require = createRequire(import.meta.url);
Does anyone know what I’m missing or if I’m making a syntax mistake?
FYI, my tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es5",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"module": "ESNext", //"CommonJS",
"skipLibCheck": true,
"outDir": "../server/frontend/dist",
"moduleResolution": "node",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"allowJs": true,
"checkJs": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"typeRoots": ["./node_modules/@types", "./src/types"],
"types": ["vite/client", "node"]
},
"exclude": [
"node_modules",
"**/node_modules/*",
"**/dist/*",
],
"ts-node": {
"swc": true,
"esm": true,
"compilerOptions": {
"module": "ESNext" //"CommonJS"
}
}
}