Guide on releasing a TypeScript component for use as a global, commonJS, or TypeScript module

I have developed a basic component using TypeScript that relies on d3 as a dependency. My goal is to make this component available on npm and adaptable for use as a global script, a commonJS module, or a TypeScript module. The structure of the component is outlined below:

/// <reference types="d3" />
class MyAwesomeComponent {
  data(data: IMyDataFormat) {
    // set data, etc.
  }
  render() {
    // do stuff with d3
  }
}
interface IMyDataFormat {
  // keys/types
}

The current configuration of my tsconfig.json file is as follows:

{
  "compilerOptions": {
    "module": "none",
    "target": "es5",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "declaration": true,
    "outFile": "./dist/index.js",
    "sourceMap": true
  },
  "include": [
    "./src/**/*.ts"
  ]
}

Upon running tsc with this setup, I obtain a file that functions effectively in the global context, making it usable by consumers like so:

<script src="./d3.js"></script>
<script src="./my-awesome-component.js"></script>
<script>
  var chart = new MyAwesomeComponent();
  chart.data([/* ... */]);
  chart.render();
</script>

How can I configure my project (e.g., through alternative tsconfig files or minor adjustments to source files) to ensure that it can also be consumed in a commonJS environment (e.g., webpack or browserify), as well as in a TypeScript project setting?

For the commonJS environment, the following should work:

const MyAwesomeComponent = require('my-awesome-component');
// alternatively:
const MyAwesomeComponent = require('my-awesome-component').MyAwesomeComponent;

And for the TypeScript environment:

import {MyAwesomeComponent, IMyDataFormat} from 'my-awesome-component';

Thank you!

Answer №1

I recently shared a sample template on npmjs.org.

  • You can find the package under the name example-93748264.
  • In addition, I have set up a GitHub repository with the source code.
  • The main guide including some instructions is provided there, but here are a few extra notes:
    • Remember to include "dom" in the libraries section of your tsconfig.json for proper compilation. (Although not always necessary, this was specifically for using d3 in a TypeScript boilerplate.)
    • Add "main": "lib/index" in your package.json. This points to the compiled output without a file extension.
    • Include "typings": "lib/index" in your package.json.
    • Even though the lib folder is excluded from version control, it will be accessible on npmjs.org.
    • Tests will run with ts-node, eliminating the need for tsc compilation.
    • To run tests in watch mode, use npm run test -- -w.
    • If you prefer to run tsc compiler in watch mode, use npm run build -- -w.

I trust these guidelines will assist you. Feel free to reach out here or create a new issue on GitHub if you have any queries.

Cheers.

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

Can you explain the process by which git hooks are installed when executing 'npm install'?

Recently, I have taken on the responsibility of managing a git repository. As I clone it and navigate to the .git/hooks directory, I find only sample hooks present. We utilize NPM as our front-end UI package manager. Upon running "npm install," actual git ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

The NPM package located in a monorepo is utilizing a local package that is not published in the N

I've been tackling a monorepo project with yarn workspaces. One of the packages is a react library that has been published to NPM. However, it relies on another package within the monorepo that hasn't been published to NPM. After installing the ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

Please indicate the decimal separator for the Number() function

UPDATE : TITLE IS MISLEADING as testing showed that Number() returned a dot-separated number and the HTML <input type="number"/> displayed it as a comma due to locale settings. I changed to using an <input type="text"/> and filtered keydown lik ...

What is the optimal approach for managing server-side data stored as a JavaScript variable?

When dealing with global variables like JSON inserted into a web page server side with PHP, the best way to handle it is up for debate. Options might include leaving it for garbage collection, omitting var initialization and deleting the variable, or simpl ...

"Enhance your gaming experience with Three JS special effects

I'm in the process of creating a multiplayer web game using Three JS. So far, I have successfully implemented the game logic on both client and server sides, mesh imports, animations, skill bars, health bars, and the ability for players to engage in c ...

Creating a shimmering glow for a dynamic AJAX div block in real-time

I created an Ajax code that retrieves results from a txt file in real time, which are then automatically displayed in a div block using the following lines: if (xmlhttp.responseText != "") { InnerHTMLText = xmlhttp.responseText + document.getElementBy ...

Transforming an HTML5 game into a native mobile application

I'm currently working on creating a HTML5 game. While I find HTML5 to be the most user-friendly programming language, I am facing an issue. I want my game to run as a native application on desktops (Windows, Mac, and Linux) rather than in a web browse ...

Resolving issues with CSS placement and resizing

I have been considering developing a UI toolkit that offers an intuitive and powerful way of setting the position and size of elements/widgets. Here are some examples of how it could be used (although they are not currently implemented): ui("Panel").size( ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Browserify Tutorial: Calling Functions from a Browserify-Generated File in the Browser

I recently delved into the world of nodejs and browserify, and my journey began with this link. Within my file main.js, you'll find the following code: var unique = require('uniq'); var data = [1, 2, 2, 3, 4, 5, 5, 5, 6]; this.LogData =f ...

Attempting to control an array of objects

In my current records: The parts with IDs 14.3, 14.2, and 14.1 belong to part ID = 30. The goal is to achieve the following: 1) By default, the first two IDs will be selected. If a user tries to select ID = 71, which belongs to part 30, they should not ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Tips for addressing Navbar collision with body content or other pages using CSS

I have successfully created a navigation bar using CSS and JS. The image below illustrates the example of my navigation bar: https://i.sstatic.net/2l4gj.png The issue I am facing is that when I select "MY ACCOUNT," it displays some content. However, upon ...

Glistening: sending reactiveValues to conditionalPanel

Is it possible to pass a reactiveValues to the condition of a conditionalPanel? If so, what is the correct method? Below is my attempt in the UI.R file for the conditionalPanel: conditionalPanel(condition = "values.cond == 0", etc. I have defined values ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

Could not locate module: Issue: Unable to resolve './Firebase'

I'm a beginner with React and I've been working on setting up Firebase in my React application. import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; var fire ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...