How to upload a TypeScript package to NPM for installation using both import and CDN methods

I am eager to publish my TypeScript project on NPM. I am currently using the TypeScript Compiler (tsc) to transpile the .ts files of my project into output .js file(s).

To generate the output files, I simply use the tsc command.

Here is my tsconfig.json:

{
  "compilerOptions": {
    "outDir": "dist",
    "declaration": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5"
  }
}

Once published, my package can be installed using:

npm install mypackagename

and can be imported in TypeScript like so:

import MyLib from 'mypackagename'

It works! However, I am interested in offering two types of installations: through npm/import (as shown above) and via CDN:

<script src="//unpkg.com/mypackagename"></script>

Is this possible? Do I need to utilize a bundler instead of the TypeScript Compiler?

Currently, it seems impossible as I am unable to directly use commonjs code in a browser.

Answer №1

After much anticipation, I implemented the Webpack bundler with specific configurations: output.library and output.libraryTarget by using UMD.

libraryTarget: 'umd' - This setting exposes your library within all module definitions, enabling compatibility with CommonJS, AMD, and as a global variable. Refer to the UMD Repository for further insights.

Hence, my webpack.config.js appears as follows:

const path = require('path')

module.exports = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-output-file.js',
    library: 'MyLib',
    libraryTarget: 'umd',
    libraryExport: 'default',
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
}

Moreover, the tsconfig.json structure looks like this:

{
  "compilerOptions": {
    "outDir": "dist",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

Thanks to these developments, my package now supports installation via import in ES6/TypeScript:

import MyLib from 'my-lib'

...or alternatively through unpkg CDN:

<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e535767266350504f415f41">[email protected]</a>"></script>
<script>
    var inst = new MyLib()
</script>

Explore the source code of my endeavor at: https://github.com/cichy380/simple-custom-event

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

Utilizing npm within a Rails application, hosted on the Heroku platform

Looking for a way to incorporate the compilation of my front end assets (typescript/minifier/handlebars), as part of a post deploy process. This will ensure that I always have fresh files without needing to check them in. Struggling to set up npm on a Her ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

Can you explain the purpose of the "-g" flag when used in the command "npm install -g <something>"?

I've been noticing the -g flag being used in examples with the npm install command, but I haven't been able to determine its function through the available help resources. ...

Having trouble establishing a connection to the TyreORM Module database while using a Postgres Docker image

I am currently developing a NestJS Application and have integrated TypeORM to connect with my local database. The database is a postgres image running in the background. Although I am able to connect to the image using pgAdmin, I am encountering an error ( ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

Visual Studio build is disrupted by the presence of node_modules folder

I am currently in the process of integrating Angular (v4) into an existing ASP.NET MVC 4 application. Within this application, there is a project that includes Selenium Web Driver along with a web.config file. node_modules\selenium-webdriver\lib ...

Fulfill the promise once the callback has been triggered

In my code, I am working on preventing the method _saveAddress from being executed multiple times. To achieve this, I have created a promise for the method. const [pressEventDisabled, setPressEventDisabled] = useState(false); <TouchableOpacity style={s ...

Creating localized versions of your React application is a breeze with i18next JSON mapping

Before anything else, please note that a translator is being used due to lack of proficiency in English. What is the best way to render a static i18next json file for multilingual support in a React application? Technologies used: React, Typescript, Styl ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...

When you sign up for the service, you might receive null values in return

I am currently in the process of subscribing to a service that needs access to the REST back-end using the specified object. export class Country { iso: String; iso3: String; name: String; niceName: String; numCode: number; phoneC ...

Obtain the selector from the parent element

Hello everyone, I am currently working on developing a parent class called Event that will manage the DOM for four child classes: vote-event, view-event, my-events, and my-votes. The concept is to have a single HTML file, a parent Component, and four chi ...

Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working ...

Is it possible for OpenFin to store logs in a secure database and what is the process for accessing logs located at %LocalAppData%openfinapps<app>app.log

System Information Here are the details of the system setup: OpenFin Process Manager Version: RVM = 8.1.0.4 Node.js: v16.15.0 Windows 10 Angular Application with C# .NET backend Issue: The current setup saves all application logs locally on users' ...

Runtime error caused by incorrect Typescript version detected in Visual Studio Code

After updating to VSCode 1.6.1 and switching from Typescript 1.8.10 to 2.0.3, my project stopped working. The Reflect methods have changed causing Routing-Controllers to throw an error when trying to get method attributes: TypeError: Reflect.getMetadata ...

What is the best way to categorize elements in an array of objects with varying sizes based on two distinct properties in JavaScript?

I am faced with a scenario where I have two distinct arrays of objects obtained from an aggregate function due to using two different collections. Although I attempted to utilize the map function as outlined here, it proved unsuccessful in resolving my is ...

Utilize the power of meteor-dburles-collection-helpers in TypeScript for optimizing your collections

Currently, I am utilizing the dburles:collection-helpers in my Meteor 2.12 project that is integrated with TypeScript. The package was included through meteor add dburles:collection-helpers, and the types were added using meteor yarn add @types/meteor-dbur ...

Can [email protected] be used to test *.ts files?

I have a question but unfortunately, I cannot seem to find any information about it. My node version is stuck on 4.2.2, which means I am unable to use ts-jest as it requires at least <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

Node.js built-ins require shims, while global variable names are absent

After updating my project using npm-check-updates, I encountered a strange error that stumped me. Despite following the suggested terminal command to install polyfill-node, the issue persisted with no resolution in sight online. The error displayed on the ...

Graphql is a revolutionary method for structuring entities in a hierarchical schema

Hey there! I'm fairly new to the world of GraphQL, and I've been curious about whether it's possible to organize entities into a tree schema similar to how Swagger handles it. I'm using Apollo Server for my UI/debugging of my GraphQL. ...