简体   繁体   中英

Declaration for Module Exporting Object

I have a project that compiles and exposes two CommonJS modules; each of them an object. Then, I have another project that consumes them.

The project structures are as follows:

multi-mod-package
|-mod1
| |-index.js
|-mod2
| |-index.js
|-package.json
multi-mod-consumer
|-index.ts
|-package.json
|-tsconfig.json

And the file contents:

multi-mod-package/mod1/index.js

module.exports.default = {
    "count": "One"
};

multi-mod-package/mod2/index.js

module.exports.default = {
    "count": "Two"
};

multi-mod-consumer/index.ts

import one  from "multi-mod-package/mod1";
import two  from "multi-mod-package/mod2";

console.log(`${one.count}, ${two.count}, Buckle My Shoes`);

multi-mod-consumer/tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true
    },
    "include": [
        "index.ts"
    ]
}

Without the noImplicitAny , this works fine. The project compiles, and One, Two, Buckle My Shoes is output as expected. However, the modules have no typings. I would like to enable noImplicitAny and have proper typings for these modules, so I am trying to write declaration files for each. I have tried a number of iterations of declare module and declare namespace , but I keep getting "... is not a module" errors when attempting to consume the modules.

How do I write a declaration file for a module that exports an object?

UPDATE

Adding two definition files - multi-mod-package/mod1/index.d.ts and multi-mod-package/mod1/index.d.ts - with the contents declare module "multi-mod-package/mod1"; and declare module "multi-mod-package/mod1"; - respectively - gets rid of the "... is not a module" errors. However, there is still no proper typings; one.count still comes up as type any .

When I try to give the module a body (even just an empty one), TypeScript complains that the module has no default export. So, I still need a solution for telling TypeScript the module is an object containing the count property.

You need to declare the sub-module as individual modules.

In your typings (eg typings/multi-mod-package.d.ts ):

declare module 'multi-mod-package/mod1' {
   // typings for mod1
}

declare module 'multi-mod-package/mod2' {
   // typings for mod2
}

For how to write your typings, you can check out the handbook:

https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html

TypeScript does not do automatic deeplinking because node resolution for deep linking can be different than the typings structure.

Node deep linking is resolved based on the location of package.json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM