denoland / dnt

Deno to npm package build tool.
MIT License
1.25k stars 40 forks source link

Types not being inferred #343

Open PetrosiliusPatter opened 1 year ago

PetrosiliusPatter commented 1 year ago

I'm trying to build my Deno project, but dnt is not inferring my types correctly.
I have the following code:

deps.ts

export { default as React } from "https://esm.sh/react@18.2.0"

testHook.ts

import { React } from "./deps.ts"

export const testHook = () => {
  const [isEnabled, setIsEnabled] = React.useState(false)
  const otherTestVar = false

  return { isEnabled, setIsEnabled, otherTestVar }
}

index.ts

export { testHook } from "./testHook.ts"

And the following build script: build-npm.ts

import { build, emptyDir } from "https://deno.land/x/dnt@0.38.1/mod.ts"

const outDir = "./build/npm"
await emptyDir(outDir)

const [version] = Deno.args
if (!version) {
  throw new Error("a version argument is required to build the npm package")
}

await build({
  entryPoints: ["./src/index.ts"],
  outDir,
  shims: {
    deno: false,
  },
  test: false,
  typeCheck: false,
  compilerOptions: {
    target: "ES2020",
    sourceMap: true,
  },
  package: {
    // package.json properties
    name: "redacted",
    version,
    description:
      "redacted.",
    license: "WTFPL",
    author: "PetrosiliusPatter",
    repository: {
      type: "git",
      url: "git+redacted",
    },
    bugs: {
      url: "redacted",
    },
    engines: {
      node: ">= 14",
    },
  },
})

await Deno.copyFile("README.md", `${outDir}/README.md`)

However, the resulting types are: testHook.d.ts

export declare const testHook: () => {
    isEnabled: any;
    setIsEnabled: any;
    otherTestVar: boolean;
};

So it doesn't seem to be inferring the types from React correctly! How can I fix this / what am I doing wrong?

PetrosiliusPatter commented 1 year ago

Ah, I found (part of) the problem: It's the same as https://github.com/denoland/dnt/issues/297!

I had typeCheck: false in my build script, so it didn't check & notify me about missing types.
Thanks to Deno I didn't actually have to bother with installing the react-types, but when they were missing in the build step, and I turned typeCheck on, errors were raised. (I was also missing lib: ["ES2021", "DOM"] in the compiler options, but that was a different issue.)
To include the react typings, I added this to the package-field in my build script:

    devDependencies: {
      "@types/react": "18.2.0",
    },

Then everything worked.
But this feels wrong. Having to add aditional dependencies just for the build step. And having to make sure that the I bump the version for both, if I ever update the dependency.

Is there a better solution?