Constructing an Angular 2 application using a solo TypeScript file that is compiled individually

At the moment, I am in the process of developing a Chrome Extension using Angular 2. The application includes a background.js file which handles the functionality for a long-running task that operates while the extension is active. Currently, this background.js file is separate from the Angular 2 project and is treated as an asset during the build process. While this setup functions correctly, I am eager to incorporate TypeScript into my background file.

Specifically, in this TypeScript file, I aim to access certain files from my Angular 2 project like so:

///<reference path="app/app.settings.ts"/>

I only require access to settings (constants) and business objects (classes), keeping it simple.

In order to use this project effectively as an extension, I need to compile both the Angular 2 project and the background TypeScript file into separate JavaScript files located in the same directory.

Here's what I've attempted so far:

  1. Configuring angular build to separately compile the background file

I experimented with my angular-cli.json file to try to achieve the desired outcome using a single "ng build" command. I tested out various configurations including the include and files options, but unfortunately had no success.

  1. Using a script that builds the Angular app and compiles the .ts file to the same directory

This approach seemed promising initially. I developed a script that takes one argument (the output path):

#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts

The script successfully builds the Angular project and compiles the background.ts file along with the referenced dependencies, placing everything in the designated location. However, the resulting JavaScript does not function properly, leading to errors such as:

Uncaught ReferenceError: exports is not defined
Uncaught SyntaxError: Unexpected token import

It appears that employing Webpack is necessary to resolve these issues, yet I have not discovered a method to accomplish this through the command line independently from my Angular project.

Answer №1

After successfully resolving this issue, I've decided to share my solution in case it might benefit someone else.

In my case, the key was utilizing browserify to generate a .js file that functions smoothly in browsers. Initially, global installation is required:

npm install -g browserify

The code provided in the original question had to undergo some modifications similar to the following one:

#!/bin/bash
ng build --output-path=$1
tsc --outDir $1 src/background.ts
browserify $1\\background.js -o $1\\background-browserified.js

This method allows executing a single command to construct my Angular 2 project and compile as well as transfer the distinct Typescript document to the same destination.

Although alternative module bundlers such as Webpack could have been utilized, for a scenario like mine, browserify turned out to be the most suitable choice.

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 declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

Enhancing view with Typescript progressions

My current view only displays a loader.gif and a message to the user. I am looking to enhance the user experience by adding a progress indicator, such as "Processing 1 of 50", during the data update process. The ts class interacts with a data service layer ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Employing Google Fonts in Angular results in a network error with codes [_ngcontent-X];400[_ngcontent-X];600[_ngcontent-X]

I have been encountering numerous network errors similar to the following: > Request URL: https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300[_ngcontent-c6];400[_ngcontent-c6];600[_ngcontent-c6];700&display=swap > Reques ...

Error: Platform core encountered a StaticInjectorError[t]: It is not possible to assign a value to the property '_injector', as it is undefined

This source code includes a rest API call and global variable reference. I have only utilized bootstrap CSS and omitted saving jQuery because bootstrap.js is not being used. After performing the (ng build -prod) command, I receive production build files ...

"Is it possible to differentiate between a variable that is BehaviorSubject and one that is not

I am dealing with a variable that can be of type Date or BehaviorSubject<Date | null>. My concern is figuring out how to determine whether the variable is a BehaviorSubject or not. Can you help me with this? ...

What are the steps to code this in Angular14 syntax?

Here's the code snippet: constructor(obj?: any) { this.id = obj && obj.id || null; this.title = obj && obj.title || null; this.description = obj && obj.description || null; this.thumbnailUrl = obj && obj.thumbnailUrl || null; this. ...

Everything seemed to be going smoothly with my page, until out of nowhere I encountered an error while trying to compile

click here for image description Compilation Errors: ERROR in ./node_modules/body-parser/lib/read.js 20:11-26 Module 'zlib' not found in 'D:\BooksGalore app\frontend\node_modules\body-parser\lib' BREAKING CHA ...

How can I resolve the issue of mobileQuery.addEventListener not functioning in Safari while using Angular?

I have been utilizing the angular material sidenav, which includes specific breakpoints for different device widths. Here are some examples: View Angular material documentation example Access the same example in stackblitz This is how it appears: public ...

Utilize the Webpack library and libraryTarget settings to establish our own custom library as a global variable

I currently have a library named "xyz" that is being imported as a node module from the npm registry. Now, I want to incorporate it as a library and make it accessible under the global name "abc". To achieve this, I plan to utilize webpack configuration. ...

In the absence of localstorage, what alternatives do we have for storing values?

I need a solution to store my value without using local storage, as the value can be visible in the developer tools with local storage. Is there a method to store a value that is hidden from the developer tools? Any guidance would be appreciated. Thank yo ...

"Error: In TypeScript, the Child Method is not recognized within the Parent

I'm a newcomer to TypeScript and object-oriented programming. I am attempting to use a method from a child class in the parent class, but for some reason, the method is not being recognized. Below is my Child class: import {Ouvrage} from "./Clas ...

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

Issue with third-party react module (effector) causing Webpack error

UPDATE: After struggling with my own custom Webpack setup, I decided to switch to using react-scripts, and now everything is compiling smoothly. It seems like the issue was indeed with my Webpack/Babel configuration, but I still can't pinpoint the exa ...

The return type is not undefined but the switch covers all possibilities

I'm struggling to understand the issue with this simple example interface List { "A": false, "B": false, } // The function is missing a return statement and its return type does not include 'undefined'.ts(2366) / ...

Navigating through an array in Angular 5: a guide

This question may seem simple, but I'm having trouble figuring it out. Here is the code snippet I am working with: getInstabul(): void { this.homeService.getWeather() .subscribe((weather) => { this.instanbulWeathers = weather ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

What is the best way to ensure observables in a template (using async pipe) are fully subscribed to before executing any initialization code?

I am facing an issue with my HTTP service that returns information based on a given item ID. The data is fetched using a Subject, which receives the initial data in the ngOnInit method. To display the returned data in the HTML, I utilize the async pipe. ...

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

What is the process for accessing a different view and its features on a separate screen using Angular portal?

In my angular project, I have multiple components. One component is being looped with an array using the following code: <body-chart *ngFor="..."></body-chart> Within the body-chart component : <div> <canvas id="canv ...