Importing Angular 2 typescript into nested directories

If my file structure looks like this:

  • app
    • models
      • model1.ts
      • model2.ts
      • model3.ts
      • index.ts
    • services
      • serviceGroup1
      • serviceGroup1Service1.ts
      • serviceGroup1Service2.ts
      • index.ts
      • serviceGroup2
      • serviceGroup3
      • index.ts

In the tsconfig.json file:

"compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "mapRoot": "/",
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../dist/",
    "rootDir": ".",
    "sourceMap": true,
    "target": "es5",
    "inlineSources": true
}

How can I make all models public and import them like this in serviceGroup1Service1.ts:

import * as models from 'models';

Updated file tree

Updated files

I added new barrels to system.config.ts

'app',
'app/models',
'app/services'

When trying to use it in serviceGroup1Service1.ts

import * from 'app/models'

I get an error saying "Cannot find module 'app/models'

However, importing components like this works fine:

import { Component } from '@angular/core'

How can I do it for my components?

Answer №1

Include app/models.ts in your project:

export * from './models/modelA'
export * from './models/modelB'
export * from './models/modelC'

You can now easily import them using:

import * as models from 'app/models';

To use just models instead of app/models, you'll need to add a SystemJS map configuration, like this:

System.config.map = { models: 'app/models' }

Answer №2

While the previous answer is effective, I've observed a pattern in Angular2 known as "barrels," where an index.ts file in the models directory exports all files using "export * from xxx", followed by importing it using "import * from ./models/". Both methods are functional, but this particular pattern caught my attention.

There may be some native support for generating barrels, possibly in angular-cli. When I utilized it to create a component, the barrels were automatically generated. However, I have only needed a few and created them manually when required.

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

What is the process for creating documentation for a TypeScript enum type with the format of { [key]: value }

I am currently developing a logger service for nodeJS using Typescript. One important component of this project is an enum that looks like this: enum LOG_TYPES { NONE = 0, ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4, } Along with the enum, I have i ...

utilizing regular expressions in TypeScript

I'm currently working with Angular 2 and I have a URL link: www.abcd.com/Computers_Accessories/panache-air-pc/P-coac-20620024815-cat-z.html#newId=P-coac-41130779424?trackId=paym&subTrackId=&infitag=1234 My goal is to remove the portion #newId ...

Number as the Key in Typescript Record<number, string> is allowed

As a newcomer to TypeScript, I am still learning a lot and came across this code snippet that involves the Record utility types, which is quite perplexing for me. The code functions correctly in the playground environment. const data = async (name: string ...

Utilizing event listeners with image elements in React for interactive typing experience

When I attempt to type the event as React.ChangeEvent<HTMLImageElement> in order to make the e.target.src work, I encounter the following error messages in the imageFound and ImageNotFound functions: Type '(evt: React.ChangeEvent) => void&a ...

How do you implement an asynchronous validator for template-driven forms in Angular 2?

I have created a custom directive for my asynchronous validator: @Directive({ selector: '[validatorUsername]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }] }) export class ValidatorUsern ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Angular 6 Progressive Web App Error: JSON Parsing Issue at Beginning of JSON Data

Recently, I updated an Angular application from version 5 to 6. Previously, the service worker was functioning properly. However, after building the production build using 'ng build -- prod', I encountered the following error... Error:- Unexpe ...

You appear to be missing a dependency on either "@angular/core" or "rxjs" when attempting to deploy your MEAN app on Heroku. This issue must be resolved

I encountered an issue while trying to deploy my MEAN-stack application on Heroku. My app was built mainly following this tutorial series. However, during the deployment process by pushing to GIT, I received the following error: <a href="/cdn-cgi/l/emai ...

utilizing a decimal point that is not in accordance with my cultural norms

I have encountered a bug where, despite setting the language of Windows 10 to Italian and adjusting the decimal separator in the control panel, our website is unable to display numbers with it. Is there a way to instruct devextreme to use the comma speci ...

Using JavaScript or TypeScript to locate the key and add the value to an array

My dilemma involves an object structured as follows: [{ Date: 01/11/2022, Questionnaire: [ {Title: 'Rating', Ans: '5' }, {Title: 'Comment', Ans: 'Awesome' } ] }, { Date: 01/11/2022, Questionnaire ...

Learn how to restrict input to only specific characters in an input box using Angular2 and validations

Is it possible to restrict user input in an input box to only specific characters such as '7' and '8'? I tried adding validations with attributes like type="number", min="7" and max="8", but even then other keys can be inserted before v ...

Angular 5 Image Upload - Transfer your images with ease

I am having trouble saving a simple post in firebase, especially with the image included. This is my current service implementation: uploadAndSave(item: any) { let post = { $key: item.key, title: item.title, description: item.description, url: '&a ...

Using the assert statement in asynchronous functions in TypeScript

I have a block of code similar to the following, which contains a function utilizing async. Whenever I insert an assert statement within this function, it causes the code execution to halt at that specific line without throwing any errors. It simply stops ...

The Discriminate Union is ineffective in handling function arguments

Trying to create a discriminate union type for two potential component props, but encountering issues with passing the argument to the onClick function in this instance: type TLink = { label: string, onClick?: (e: React.MouseEvent<HTMLAnchorElement& ...

Development in Angular 2 with a team of developers utilizing TFVC for version control and managing node_modules

With over 20,000 files in the node_modules directory, it may not be practical to include them in source control. This results in developers having to run 'npm install' every time they perform a 'get latest' in order to download any mis ...

Navigating through Vue3 script Setup and encountering a TypeScript error stating `Type 'string' is not assignable to type 'Stuff | undefined'.` - here's a clever workaround

Having an issue with Vue3's script setup syntax where a strange ts error occurs when trying to assign a variable as a prop value. I have defined a type Stuff: 'item' | 'box' | 'area' and using it as the PropType for my p ...

There is currently no loader set up for ".html" files within the Vitejs configuration, specifically for the index.html file

Hello, I have encountered a problem. I am working with Visual Studio 2022 and have created two projects within one solution - one for the back-end (ASP.NET) and the other for the front-end (Vue.js and Vite). The issue arises when I use the npm create vue@3 ...

The attribute 'value' is not recognized on this type 'IntrinsicAttributes & ChildrenProps'

Working on a project in React with Typescript is proving to be quite challenging for me. I'm attempting to implement a context to share a useState, but encountering an error when using value={{ isOpen, setIsOpen }}: Type '{ children: ReactNode; v ...

Getting the event of a directive in a dynamic component can be achieved by setting @HostDirective()

Check out this code snippet for dynamically creating a component: @Component({ selector: 'app-dynamic', template: `{{ message }}`, standalone: true, hostDirectives: [ { directive: OneDirective, outputs: ['change: mess ...

Is there a way to replace mat-button-toggle with a radio button?

Hey there, I am just starting with Angular and I'm looking to transform the code below into radio buttons. <div class="col-4"> <div class="label-icon"><label><b>Certfication Required</b></label> </div&g ...