What is the best way to bring in classes from an external module within Typescript?

I am currently in the process of transforming .NET entities into an npm module. However, I am encountering difficulties when trying to utilize it within my Angular2 component.

Here is the overall structure of the module: enter image description here

In order to satisfy the referenced types, we have decided to create a module and import from index.d.ts (within npm).

declare module cio {
export class Address {
    addressLine1: string;
    addressLine2: string;
    city: string;
    state: string;
    country: string; 
    postalCode: string;
}

. . .

declare module cio {
 export class Business {
    id: string;
    typeName: string;
    createdDate: Date;
    lastModifiedDate: Date;
    createdBy: string; 
    lastModifiedBy: string;
    isTest: boolean;
    isDeleted: boolean;
    taxId: string;
    businessType: BusinessType;
    businessName: string;
    address: Address;
    phone: string;
    mobile: string;
    fax: string;
    email: string;
}
enum BusinessType {
    Individual = 1,
    Company = 2,
}

}

I attempted to import by using:

import { Address, ... } from 'npm_module_name/index';

And then created an object like this:

let testAddress : Address = new Address();

Error:(31, 16) TS2304:Cannot find name 'Address'.

I also tried importing in this manner:

import { cio } from 'npm_module_name/index/';

And created an object like this:

let testAddress : cio.Address = new cio.Address();

Error:(31, 20) TS2694:Namespace ''*'' has no exported member 'Address'.

I experimented with replacing "module" with "namespace," but that did not resolve the issue.

What would be the best approach for importing into my component? Thank you.

Answer №1

In my recent experience, I encountered a situation where I needed to perform the following actions.

Firstly, it is crucial to ensure that you have the correct TypeScript configuration set up in your npm package's `tsconfig.json` file. The key elements to focus on are outlined below:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "lib": ["es6", "es2017", "dom"]
    }
}

The concept here is to utilize the npm package name as the module. Therefore, when using this package, you can proceed as follows.

import {items} from "YourFantasticPackage"

The npm module's name is derived from your `package.json` file. Within this file, you can also specify the main file in the distribution and the location of your type definitions. A simplified example is shown below (excluding additional details for brevity).

{
  "name": "YourFantasticPackage",
  "version": "2.0.0",
  "main": "dist/index.js",
  "typings": "dist/definitions/index",
  "typescript": {
    "definition": "dist/definitions/index"
  }
}

During my build process (implemented using gulp), I opted to generate `./index.ts`, which simply exports everything from my package. To achieve this, I utilized gulp-create-tsindex. This generates an `index.ts` file structured like the example below:

export * from "./dir1/file1";
export * from "./dir1/file2";
export * from "./dir2/file1";
export * from "./dir2/file2";
...

Please note that `gulp-create-tsindex` flattens the folder structure. Therefore, even if `items` resides in `dir1/subdir2/someitems.ts`, you must still import it using the specified syntax (`import {items} from "YourFantasticPackage"`).

A basic build task with these considerations appears as follows:

const ts = require("gulp-typescript");
const tsProject = ts.createProject("path/to/tsconfig");
const tsindex = require('gulp-create-tsindex');
const merge = require('merge2');

gulp.task("build-ts", function() {

    const tsResult = tsProject.src()
        .pipe(tsindex('path/to/src/folder/index.ts'))
        .pipe(tsProject());

    return merge([
        tsResult.dts.pipe(gulp.dest('path/to/dist/folder/definitions')),
        tsResult.js.pipe(
            gulp.dest('path/to/dist/folder')
        )
    ]);
});

I trust this information proves beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a Dynamic Form Array with Options for Selection

I am facing an issue with reactive forms and a radio button array in my project. The problem is that I can only select one package at a time instead of multiple packages. Can anyone guide me on how to enable the selection of multiple packages? You can view ...

The error thrown by Handsontable is that it cannot locate the modules numbro, moment, pikaday, and ZeroClipboard

I've included handsontable-pro, numbro, moment, pikaday, and ZeroClipboard in my application's dependencies listed within the package.json file, for example: "dependencies": { "numbro": "^1.9.0", "moment": "^2.14.1", ... } I have a ...

Obtaining the directory of a node package in a visual interface

As a newcomer to NodeJS, I am diving into using a plugin named videojs-playlist alongside video-js. According to the documentation, the plugins should be included as follows: <script src="path/to/video.js/dist/video.js"></script> <script s ...

Export the npm package dependencies to a text file

When developing, I often find myself switching between different computers. One would think that with npm and my package.json, everything would be consistent when checked out, at least on the same major version like ~4.0.0. However, I've noticed a sig ...

The template is displaying the string as "[object Object]"

I've implemented code in my ngOnInit function to fetch the translation for a specific text. The following function is being called: async getEmailTranslation() { const email$ = this.translate.get('SUPPORT_TRANSLATE.EMAIL'); this.emai ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Switch up the data format of a JSON file that is brought into TypeScript

When bringing in a JSON file into a TypeScript project with the resolveJsonModule option activated, the TypeScript compiler can automatically determine the type of the imported JSON file. However, I find this type to be too specific and I would like to rep ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...

Install npm packages without rebuilding node-gyp

Is there a way to run npm install without running node-gyp rebuild, since doing so in my post install scripts causes an error? ...

Invoke the method whenever the text input is modified

I'm currently utilizing Angular 5 along with Materialize, and the datepicker feature is functioning flawlessly: <input materialize="pickadate" type="text" class="datepicker" placeholder="Select Date" [materializeParams]=datePickerParams> W ...

What is the best way to incorporate debugging functionality into a TypeScript project that will be bundled using rollup?

I have been working on an Angular 2 project and encountered no issues while using debug. However, when I attempted to integrate rollup, I faced the following error: Cannot call a namespace ('debugModule') This error is related to how I import d ...

Updating JSON dependencies in NPM and manually fixing vulnerabilities

After spending a day trying to manually fix multiple high vulnerabilities, I realized it was a futile effort. Despite reading numerous posts, blogs, and suggestions, I couldn't resolve the issue. The root cause seems to be that /css-what requires an ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

How can I establish a connection to a Unix socket path using a connection string with Slonik?

Hey there! I encountered an issue while attempting to connect to a Google Cloud database using slonik: const pool = createPool( `socket:userName:password@/cloudsql/teest-123986:europe-west3:test?db=dbName` ) The error message I received was: error: throw ...

Utilizing generic optional parameters in Typescript function overloads

I am currently attempting to create a higher-order function that wraps the input function and caches the result of the most recent call as a side effect. The basic function (withCache) is structured as follows: function cache(key: string, value: any) { ...

An error occurred while trying to access the property "xxx" of an undefined object within the updateDirectives function

Experiencing an issue: Encountering a 'Cannot read Property of Undefined Full_Name' error at Object.eval <ion-item> <ion-label position="floating">Full Name</ion-label> <ion-input id="name" name=Full_Name #Full ...

The Angular 7 application is experiencing a CORS error when accessed from the Angular client

After creating an angular 7 app with an express backend, I have encountered an issue. The Express server is running on localhost:3000 while the Angular client is on localhost:4200. In my server.js, here is a snippet of the code: const app = express(); // ...

Node: Oops! Looks like I can't locate the module

After setting up Node and NPM using Homebrew, I proceeded to install Susi: npm install -g susi /Users/oliver/.node/bin/susi -> /Users/oliver/.node/lib/node_modules/susi/susi <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65 ...