Group multiple typescript files into separate outFile modules

Can TypeScript files be grouped into multiple outFiles? I want to bundle my Typescript code, but instead of one single JS file, I would like to organize my TS into separate JS files such as controllers.js and plugins.js. The options in the TypeScript project only allow for one outFile selection. Is there a way to achieve this?

Answer №1

Regrettably, the default TypeScript compiler behavior does not address this issue. I encountered this problem myself while attempting to modularize a TypeScript application.

My chosen solution for this problem is as follows:

  1. Revert back to using traditional _references.ts files.
  2. Avoid bundling with TSC (simply compile to JavaScript).
  3. Utilize a Gulp plugin/function to parse _references.ts files. Here is my approach:

var fs = require('fs');

// Constants
var PLUGIN_NAME = 'reference-parser';

// Plugin function for file processing
function referenceParser(fileName, prefix, filterParentReferences) {
    var references = [];

    var content = fs.readFileSync(fileName, 'utf8');
    content = content.replace(/\/\/\/ <reference path=("|')/g, prefix);
    content = content.replace(/.ts("|')\s*\/>,?/g, '.js');

    function readLines(input) {
        if (input.length === 0)
            return;

        var newLineIndex = input.indexOf('\r\n');
        if (newLineIndex >= 0) {
            var line = input.substring(0, newLineIndex).trim();

            readLine(line);

            if (input.length > (newLineIndex + 2))
                readLines(input.substring(newLineIndex + 2));
        } else {
            readLine(input);
        }
    }

    function readLine(line) {
        if (line && line.length > 0) {
            //console.log('Line: ' + line);

            if (line.startsWith('//')) {
                //console.log('Comment line, ignored.');
            } else if (line.indexOf('_references.ts') >= 0) {
                //console.log('External reference line, ignored.'); // TODO Support this?
            } else if (filterParentReferences && line.startsWith('../')) {
                //console.log('Parent reference, ignored.');
            } else {
                references.push(line);
            }
        }
    }

    readLines(content);
    return references;
}

// Exporting the main plugin function
module.exports = referenceParser;

b. Combine everything in a Gulp task:

//...

        // Retrieve module source files by parsing the module's _references.ts file.
        var sourceFiles = referenceParser(sourceRoot + '_references.ts', buildJsRoot, true);
        // console.log(sourceFiles);
        var sourcesStream = gulp
            .src(sourceFiles)
            .pipe(plugins.sourcemaps.init({ loadMaps: true })) // Load TypeScript generated source maps
            .pipe(plugins.concat(module.name + '.Bundle.js'))
            .pipe(plugins.uglify({ mangle: false })) // Minify the resulting bundle
            .pipe(plugins.sourcemaps.write('.')) // Write the merged bundle source maps
            .pipe(gulp.dest(destinationRoot));
        moduleGulpStreams.add(sourcesStream); // Add the source stream to the stream merger

//...

Answer №2

To make this happen, simply generate several tsconfig.json files. Afterwards, execute the compiler separately for each output file:

tsc -p /path/to/first/tsconfig.json --outFile controllers.js
tsc -p /path/to/second/tsconfig.json --outFile plugins.js

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

Dealing With HttpClient and Asynchronous Functionality in Angular

I've been pondering this issue all day. I have a button that should withdraw a student from a class, which is straightforward. However, it should also check the database for a waiting list for that class and enroll the next person if there is any. In ...

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

My component is missing the ChangeDetectorRef in Nativescript

I am attempting to automatically update an array within a Listview by utilizing ChangeDetectorRef in the following way: import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from "@angular/core"; @Component({ selector: "regi ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

Updating the default value for react-i18next (stored in localstorage)

When utilizing a backend and language detector, an issue arises: The localstorage contains the key I18nextLng with the value en-US. How can we set the default value to be I18nextLng with the value En? init and other settings are as per the default docume ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

The search is on for the elusive object that Angular 2/4

Why am I encountering the error message saying "Cannot find name 'object'"? The error message is: Error: core.service.ts (19,23): Cannot find name 'object'. This error occurs in the following line of code: userChange: Subject<ob ...

The properties are absent in Angular Service - Observable

I recently started learning angular and I'm struggling to make this HTTP get request work. I have been looking at various examples of get requests for arrays and attempted to modify one for a single object (a user profile) but without success. The err ...

Attempting to intercept a 401 error in an HTTP interceptor, I aim to refresh my session and then retry the initial request

My goal is to intercept responses returning from the /api, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occu ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here&apo ...

JavaScript - Cannot access the 'name' property on an empty object

I am currently following a React tutorial that demonstrates how to create a useForm hook for linking form input to state. Here is the implementation of the hook: const useForm = (initial = {}) => { const [inputs, setInputs] = useState(initial) ...