reactjs – How to build my type script component(hook) with ESnext and CommonJS to publish this to npm?

my build script is this:

 "clean": "rimraf dist",
 "tsc-build": "npm run clean && tsc --p tsconfig.json --module esnext && tsc --p tsconfig.json --module commonjs"

As far as I know, if you build with esnext, you should have an index.mjs file.
However, the build result is as follows:

my outdir

And if i “import” this in other project, error occurs: Module not found: Error: Can’t resolve ‘my module’ in ‘projectdir\src’

How to build my React Component(hooks) both esnext and commonjs?

this is my package.json

 "main": "dist/index.js",
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.js"
    }
  },
  "types": "dist/index.d.ts",
  "license": "MIT",
  "files": [
    "dist/"
  ],

this is my tsconfig.

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "declarationMap": true,
    "jsx": "react-jsx",
    "moduleResolution": "node"
  },
  "include": ["src/components"],
  "exclude": ["node_modules"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Read more here: Source link