Tips for bundling a substantial Typescript framework using Webpack

In my endeavor to construct a TypeScript framework and bundle it using Webpack, I have encountered a perplexing issue. The problem lies in determining the appropriate "entry point" - setting it to all files results in only the final built file being accessible to the browser.

Conversely, selecting a single entry point causes only that specific class to be exposed while leaving out dependent classes within the framework. Hence, striking a balance with the entry point is crucial for seamless functionality.

Insight:

The scope of my TypeScript framework is extensive; currently comprising 140 modules, which will expand to over a thousand upon completion. Each module under the "bean" category includes an exported class along with several import statements referencing other modules within the framework.

The hierarchical folder structure is as follows:

+---src
|   +---API
|   +---bean
|   |   -- various modules --
|   +---enums
|   +---typings
|   \---util

Each 'impl' directory contains an exported class, while parent folders house corresponding interfaces.

This framework isn't designed as a standalone application or library but is intended for users to utilize specific classes like so: `var f = new CodeListBeanImpl();`

The rationale behind these individual files stems from a defined structural hierarchy; each class serves a distinct purpose within the broader framework architecture.

Despite the scattered nature of these files across different locations, there is a lack of a definitive "entry point," impeding webpack from efficiently bundling all modules into a singular file accessible by the browser.

Here's a glimpse at my webpack configuration:

const CircularDependencyPlugin = require('circular-dependency-plugin');
const path = require("path");
const glob = require("glob");
let list = glob.sync("./src/**/*.ts");

// webpack config settings

module.exports = {
    entry: list,
        // other configurations...
};

The challenge arises when attempting to gather all modules comprehensively through the entry point mechanism; either choosing every file or a specific one leads to drawbacks in accessibility and functionality. It prompts me to explore alternative packers to address this limitation effectively.

For further reference, here is my tsconfig.json file governing the TypeScript compilation settings.


{
  "compilerOptions": {
      // compiler options details...
  },
  "include": ["./src/**/*.ts"]
}

Answer №1

I successfully achieved my goal by creating a file named "main.ts" outside of the src folder and dynamically generating exports for each class.

Although this method works, I am still open to better suggestions:

Here is the webpack configuration code snippet:

 function createEntryPoint(){
        console.log("creating entry point...");
        const glob = require("glob");
        let typeScriptConfigFile = require("./tsconfig");
        let baseUrl = typeScriptConfigFile.compilerOptions.baseUrl;
        if(!baseUrl){
            throw new Error("Unable to find baseUrl in tsconfig");
        }
        let list = glob.sync(baseUrl+"/**/*.ts");
        const fs = require('fs');
        let num = 0;
        fs.writeFileSync('./main.ts', (function () {
            let strToReturn = "";
            for (let file of list) {
                num++;
                let fromBaseUrl = file.replace(baseUrl+"/", "");
                fromBaseUrl = fromBaseUrl.replace(".ts", "");
                strToReturn += "export * from '" + fromBaseUrl + "'; \n";
            }
            return strToReturn;
        }()));

        console.log("Entry point created: " +num + " modules exported");
    }
    createEntryPoint();

The specified entry point in the webpack configuration is:

entry: "./main.ts",

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

Encountered an error during the execution of the [email protected] postinstall script

I encountered an issue while attempting to install electron in my project. I even tried using unsafe-perm, but the error persisted. npm install electron --save-dev --save-exact > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Having difficulties with the installation of expo-cli: Dependency resolution unsuccessful

npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1e131a0f470c0f191e2a5a445f4458">[email protected]</a> npm ERR! ...

Netlify Reports Gatsby Build Error

I am encountering a build error while trying to deploy my Gatsby WordPress experimental site on Netlify. Netlify support has confirmed that the issue lies in the build process and not with Netlify itself. However, I am unable to pinpoint the exact error c ...

What is the reason for the return of undefined with getElementsByClassName() in puppeteer?

Currently, I am utilizing puppeteer to fetch certain elements from a webpage, specifically class items (divs). Although I understand that getElementsByClassName returns a list that needs to be looped through, the function always returns undefined for me, e ...

Guide on utilizing the maven-exec-plugin to execute npm clean commands

I am currently utilizing the exec-maven-plugin in my project. I have added extensions for npm install and npm clean commands. Below is the configuration section of the plugin in the pom file, which includes extensions for npm install, tsc run, and npm clea ...

Customize the text for the material icon

Can I customize an icon by using the following code: import FiberNewIcon from "@mui/icons-material/FiberNew"; Is there a way to add custom text to the icon? ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

typescript leaflet loading tutorial

I'm attempting to replicate the basic example of loading a map with Leaflet in TypeScript, following the guidance on the Leaflet website. I am not utilizing any frameworks like Angular or React. I have installed Leaflet and types through npm. To adher ...

The error `npm run server` is not able to recognize the command '.' as an internal or external command

While working on my project from github https://github.com/angular-university/reactive-angular-course, I encountered an issue. Even though I have all the latest dependencies and am running on Windows, I am facing this problem. Interestingly, it works fin ...

Encountering type errors in NextJS with TypeScript

I am facing an issue while trying to run this function: "use server"; export const addProduct = async (formData: FormData, imageUrl: string) => { const productName = formData.get("productName")?.toString(); const description = f ...

Azure pipeline: Command Line error: Bash exited with code '1'

While attempting to run my Cypress test using Azure Pipeline, I encountered the following problem: YAML file: # To configure triggers for Azure CI see # https://docs.microsoft.com/en-us/azure/devops/pipelines/build/triggers?view=azure-devops&tabs=yaml ...

Properly implement Angular/Typescript to populate an array with chosen objects

Currently, I have an Angular application that is fetching JSON resources from a Spring Boot REST API. These resources consist of simple player objects with attributes like id, name, position, and value. On the UI, each object is displayed along with a "BUY ...

There seems to be an issue with the Angular QuickStart project as it is not functioning properly, showing the error message "(

After following the instructions in this guide for setting up VS2015, I encountered issues when trying to run the "quick start" project or the "tour of heroes" tutorial on Google Chrome. The error message I received can be found here: Angular_QuickStart_Er ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

When using node.js with MySQL, the insert statement with a WHERE clause does not execute properly

Snippet: function setValue(currentVal) { idOutput = currentVal; encodedVal = Base.encode(idOutput); var baseInsert = {ShortUrlCode: encodedVal}; console.log(idOutput); console.log(encodedVal); con.q ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

Tips for implementing the handleChange event with CalendarComponent from the PrimeReact library

Hey there! I'm currently working with the CalendarComponent from the PrimeReact library in my app. I want to update the type of event being typed in the handleChange function instead of leaving it as :any. Can anyone provide some suggestions on what s ...

Harnessing the Power of NextJS Image Component and @svgr/webpack for Seamless Integration

I have recently set up a Next.js site utilizing the @svgr/webpack library. In order to start using an SVG image with the new next/image component, I configured my next.config.js file accordingly. My next.config.js setup looks like this: module.exports = { ...

Ever thought about harnessing the power of SassDoc to create detailed documentation for your sass

After experimenting with sassdoc for documenting our sass mixins and functions, I realized that there doesn't seem to be a straightforward way to generate documentation for our sass variables. Specifically, I am looking for a solution that can output ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...