2

I'm setting up a monorepo for React frontend(Vite) and Express backend in typescript. I can't make both react and express happy when I import modules from shared package, because React uses ESNext and Express uses commonjs for "module" in tsconfig.json. Is there a way to bypass this?

Currently I set target of my common package to ESNext and Express will complain like SyntaxError: Unexpected token 'export'

If I remove ESNext target, Express will be happy but React starts complaining like The requested module '/@fs/Users/kdk/Desktop/saas-template/shared/dist/models/Example.js' does not provide an export named 'default'

Project structure looks like this

root
| package.json
| tsconfig.json
| frontend
    | package.json
    | tsconfig.json
|
| backend
    | package.json
    | tsconfig.json
|
| shared
    | package.json
    | tsconfig.json

frontend/tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "references": [
    { "path": "./tsconfig.node.json" }, 
    { "path": "../common" }
  ]
}

backend/tsconfig.json

{
  "compilerOptions": {
    
    "target": "es2016",                                 
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "references": [{ "path": "../common" }]
}

common/tsconfig.json

{
    "compilerOptions": {
        "target": "ESNext",
        "baseUrl": "../",
        "rootDir": "./",
        "outDir": "./dist",
        "composite": true,
        "moduleResolution": "node",
    },
    "include": ["./**/*"],
    "exclude": [
        "node_modules",
        "./dist/**/*"
    ],
}
kidox
  • 61
  • 1
  • 6
  • 1
    Does this answer your question? [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export) – jsejcksn Oct 07 '22 at 22:06
  • Did you ever solve this? I’m currently going through this and trying to update everything to esmodules on the server side…it’s fun playing with config files…! – Robert Desmond Apr 20 '23 at 22:01

0 Answers0