Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows:

[Application] -> contains -> [player] -> contains -> [renderer]

In the current setup, Renderer is an interface that needs to be swapped out for different platforms:

  • Mobile -> uses MobileRenderer
  • Web -> uses WebRenderer

I have flexibility in choosing bundlers - currently utilizing Webpack for the app and Rollup for the lib - and here's what I've managed to achieve:

My library exports a Player interface and a createPlayer function which returns a PlayerInterface. On the application side, there's a Webpack alias set up to resolve the correct platform library based on the build input.

For example:

import { createPlayer } from "my-lib";

const player = createPlayer()

We then run the application build with

npm run build --platform=web

Webpack will then convert the my-lib import into my-lib/platforms/web, which includes the exported createPlayer function utilizing the right renderer.

My query is, how can we ensure, from the application's perspective, that we are importing the correct renderer per platform during build time while still enabling tree-shaking (and only including necessary sources)? Using the build system for this purpose seems somewhat convoluted, as it lacks transparency into the process.

Is there a more efficient approach to handle this?

Regards,

Answer №1

There are a few different paths you can take. I would advise against implementing a compile-time switch, as it may result in the need to distribute multiple versions of your library, which goes against common practices. However, if you absolutely must do this, consider utilizing webpack's ProvidePlugin or resolve.alias configuration options to dynamically link your code to the appropriate renderer during the build process.

Another approach could be to offer two entry points for your application and let the user select which one to use. This method is reminiscent of how react-dom handles browser rendering versus server rendering by providing options like react-dom and react-dom/server:

// index.js

export * from './shared';
export {default as renderer} from './renderers/web';
// mobile/index.js

export * from '../shared';
export {default as renderer} from '../renderers/mobile';

In this setup, users of your library can choose between

import {renderer, foo} from 'your-lib'
and
import {renderer, foo} from 'your-lib/mobile'
.

Both of these approaches involve decisions made at build time.

Although the second option typically requires explicitly specifying the version of the library in use, webpack's resolve.alias setting allows for redirects from imports of your-lib to your-lib/mobile.

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

Attempting to change the background color of a table row when hovering in React, but experiencing no success

Describing the appearance of my table row: <tr onMouseEnter={() => {this.buttonIsHovered = true} } onMouseLeave={() => {this.buttonIsHovered = false}} className={this.buttonIsHovered ? 'hover' : null}> The initial value ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...

How can the border of the select element be removed when it is active in select2

After examining the CSS code, I am still unable to locate the specific property that is being applied to the main element. I am currently customizing the select2 library to suit my needs. However, I am stuck in the CSS as I cannot determine which property ...

Attempting to deserialize serialized data from Django using JSON.parse

I need assistance with some client-side tasks using Javascript. In my view, I serialize a Queryset from my models into JSON and pass it to the template. data = serializers.serialize("json", Profile.objects.filter(user_id=self.request.user)) This results ...

The Ultimate Guide to Automatically Updating JSON File URLs

I am currently working on a project where I need to retrieve data from a URL using the $.getJSON method. I am interested in finding a way to continuously update this data and replace it in the HTML without needing to manually refresh the page. Although I h ...

Setting up nodemon on your local machine allows for automatic restarting of

I recently added nodemon as a development dependency. As part of this, I created a script called "devserver": "./node_modules/nodemon/bin/nodemon.js index.js" However, whenever I try to run npm run devserver, it keeps throwing an error saying that ' ...

Personalize your Datatable export options with Jquery

I am working with a datatable that contains columns with data in the format 'XXXX unit'. For my export, I need to remove the 'unit' part of the data. What specific rule should I implement for this task? exportOptions: { columns: ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

What is the best way to ensure all asynchronous tasks are completed in Node.js before proceeding?

My program is in need of running numerous asynchronous tasks. Additionally, there needs to be a task that will only run once all the other asynchronous tasks have completed. Is there a way I can create a function that waits for all async functions to fin ...

Angular 2 and 4 now have a specialized node module designed to create tree-like structures within the framework

Are there any node packages available for creating tree-like structures in Angular 2 or 4, similar to what is shown here ? I am looking for the ability to customize templates within the tree. Any suggestions? ...

Adding a collection to an array in JavaScript

In my dynamic inputs, I am collecting a list of data like the following: FirstNames : Person1 FN, Person2 FN, Person3 FN, ... LastNames : Person1 LN, Person2 LN, Person3 LN, ... To retrieve these values, I use input names as shown below: var Fir ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Challenges encountered while releasing an npm package

As I followed the steps in this tutorial, I attempted to publish my package using npm publish and encountered an error npm notice npm notice ...

The edges of the cubemap in THREE.js appear murky

I am attempting to create a black skybox with white dots (stars) in three.js. However, due to the perspective effect, the dots appear darker in the corners where they are further away (as they get smaller and dimmer). Is there a way to make the appearance ...

A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be return ...

Error: Trying to access a property that is not declared on an empty object

Using a fully patched Visual Studio 2013, I am integrating JQuery, JQueryUI, JSRender, and TypeScript into my project. However, I am encountering an error in the ts file: Property 'fadeDiv' does not exist on type '{}'. While I believ ...

What is the reason behind the slight difference between TypeScript's IterableIterator<> and Generator<> generics?

In TypeScript version 3.6.3, there is a notable similarity between Generator<> and IterableIterator<>. However, when Generator<> extends Iterator<>, the third generic argument (TNext) defaults to unknown. On the other hand, Iterator ...

Connecting React.js with Socket.io for real-time communication and managing application

Hello, I am currently working on saving the response from my socket in a state via the backend. Here is a method where messages are sent to the socket: export default class Home extends Component { constructor(){ super() this.state ...