Is excluding dependencies necessary for a modular Typescript project?

I am currently in the process of developing an NPM package for a Typescript project using gulp and browserify. The challenge I'm facing is that the consumer of the package does not utilize modules. Thus, I am working on creating a standalone bundle with Browserify.

One concern I have is whether bundling all the dependencies could pose an issue. It seems that the bundled js file simply encapsulates my dependencies (three and hammerjs) within the global namespace. The consumer also includes another component that uses hammerjs (similar version), leading me to wonder which version of hammerjs will be available for my application. How do other NPM packages that function in a standalone manner address this?

I attempted to exclude dependencies in Browserify by setting bundleExternal to false or removing them individually then including those libraries in the browser. However, this approach did not resolve the issue as I encountered a "Cannot find module 'hammerjs'" error in the console. I came across information on how to use the exclude feature in Browserify and successfully browserified all the dependencies separately. Despite this workaround, it seems equivalent to bundling them together directly since I cannot directly include the hammer.min.js file from their website.

TL;DR

What is the correct method for bundling a modular Typescript NPM package and handling dependencies for usage in a non-module-supported application?

Answer №1

When creating a functional npm package, it is important to ensure that your module is located at the specified route in your package.json file as the main entry point. Typically, this would be within dist/my-main-class.js.

Within my project's src directory, I have a class/module/namespace that represents the core functionality:

class MyMainClass{
 static myMethod = function(){
    console.log('hello');
 }
}

To export this class/module, include the following line at the end of the file: export = MyMainClass;.

After publishing the package with the name MyMainClass using: $ npm publish MyMainClass, users can easily import it as shown below:

let MyMainClass = require('MyMainClass');
MyMainClass.myMethod();

Remember to build your project before publishing by including these scripts:

"build": "tsc -p .",
"prepublish": "npm run build",

If you wish to minify your code or perform other tasks, consider using gulp/webpack before publishing and targeting the dist folder.

"minify": "gulp/grunt/webpack minify dist/**.js",
"build": "tsc -p .",
"prepublish": "npm run build && npm run minify",

Answer №2

When it comes to handling dependencies, I found a solution that works for me. I decided to create two versions of my library - one with all dependencies included (mylib.js) and another without any dependencies (mylib.min.js). These are distributed in the npm package. Additionally, I provided the library in modular form for those who prefer using tools like browserify. While I initially encountered issues with browserify due to residual dependencies, switching to webpack resolved this issue seamlessly.

For reference, here is the complete structure of my project:

├───dist                
│   ├───mylib.d.ts      
│   ├───myLib.js        
│   └───myLib.min.js    
├───lib
│   ├───myLib.js        
│   └───myLib.d.ts      
├───src                 
├───tests               
└───testSrc             
    ├───test.html
    └───unittests

In my package.json file, you can find the details of my project setup including dependencies and build scripts.

The Gulpfile.js contains tasks for compiling, packing, pre-processing, copying libraries, and running tests. It automates these processes to streamline development.

The webpack.config.js file specifies the configuration for bundling the modular version of the library. By setting up externals, entry points, and output settings, webpack simplifies the process of packaging the code.

I have also manually created declaration files for TypeScript and included them for better typing support.

Finally, the test.html file references the necessary scripts for testing my library, demonstrating its usage in a practical scenario.

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

Verify that the user's input falls within a specified range before adding it to the result

Currently, I'm trying to implement validation on user input. The idea is that if a user enters a number between 1 and 10, I want to add a 0 in front of it. For example, if the user inputs 4, I would like to store the value 04. While I am comfortable d ...

What is the best way to define a npm dependency using a GitHub subfolder URL?

Check out my git repository: README.md packages common package.json main package.json Can anyone advise how to specify the common dependency in the main package.json using a github subfolder URL? I tried this but it doesn't seem to be w ...

Troubleshooting the order of Javascript execution in bundled TypeScript applications

I encountered an issue with the execution order of generated JavaScript code during bundling, resulting in an error message when everything is bundled together. An error occurred: [$injector:nomod] Module 'app.demo' is not accessible! This cou ...

Utilizing npm programmatically within Node's REPL environment

My goal is to use the npm module programmatically in order to install other modules. By placing the code below in a file.js: var npm = require('npm'); npm.load({ save : true, loglevel : 'warn' }, function (err) { if (err) ...

What is the starting point of a Next.js application?

When deploying a nextjs app on c-panel hosting, it requires the entry point of the application which is typically set as app.js by default. In a regular React application, you have full control over this aspect, but with nextjs, it's not always clear ...

Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario. private createRowData() { const rowData: any[] = []; this.http .get(`/assets/json/payment.json`) .toPromise() .then(r ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

Setting up Firebase App Check in an Angular projectWould you like to know

I have a question about initializing Firebase app check with Angular. I am currently using AngularFire, but I'm not sure how to initialize Firebase app check before using any services. The documentation provides the following initialization code to b ...

Issue: Unable to find provider for "framework:jasmine"! (Attempting to resolve: framework:jasmine)

After running the following commands on my Windows console: npm install -g yo grunt-cli bower npm install -g generator-angular yo angular I opened my project in WebStorm and right-clicked on the karma.conf.js file in the project explorer to select &apo ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

When faced with the error "Eslint prettier is throwing an error saying 'Replace typeof·TYPE with (typeof·TYPE)eslintprettier/prettier'", it's important to address it promptly to ensure

After updating eslint and all its plugins to the latest versions, I encountered this issue. Which rule is causing this? I can't seem to locate it. ...

Tips for assigning a type to a variable that is being configured in Typescript

Within my code, I am utilizing the function PanelService.getSetupOrder(route.params.id) which provides me with 4 specific variables: data pending error refresh While researching the documentation, it was mentioned that by specifying data: order, I could ...

Error message "npm: not found" was encountered while attempting to generate a React app using tools like NVM and NPM within

I'm currently working on setting up a new React project in pycharm. Utilizing version 0.34.0 of NVM, I have successfully installed node. Before initiating the project, here is my pycharm window: https://i.stack.imgur.com/Opt7z.png The command npm - ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

Having difficulty with installing the ttf-loader for React with Typescript

Currently, I am working on a project using React with TypeScript and trying to incorporate the font feature in react-pdf/renderer. The font has been successfully imported and registered as shown below: import { Text, View, StyleSheet, Font } from "@re ...

"Embedding a JSON object within a script tag in NextJS: A step-by-step

I've been working on configuring values within a Cookiebot initialization script tag in a NextJS project. The documentation suggests that I can set vendor properties by passing in a JSON object inside the script tag, like this (taken from this link): ...

What could be causing the ngOnInit() method to execute before canActivate() in this scenario

When working with route guards, I am using the canActivate() method. However, I have noticed that Angular is triggering the ngOnInit() of my root AppComponent before calling canActivate. In my scenario, I need to ensure that certain data is fetched in the ...

The declaration file (d.ts) is unable to access the type declaration

I am facing an issue with the following directory structure: dts/ my-types.d.ts lib/ a.ts a.d.ts b.ts b.d.ts Both a.ts and b.ts reference a common type called IFoo. To avoid redundancy, I decided to declare IFoo in a shared file located at dts ...

What are the main distinctions between the files found in NPM repositories and GitHub repositories?

Is it possible for the GitHub repository and the NPM repository to have different contents? I'm curious about how this could happen and if it poses a security risk. Despite my research efforts, I couldn't find satisfactory answers. Even seemingly ...

I encounter a connection refusal from localhost whenever I try to set up setupProxy.js

I created a solution with setupProxy.js to address a CORS issue: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( proxy('/myUrl', { target: 'http://localhost:8090&a ...