What is the process for invoking TypeScript functions outside of the .ts files?

Embarking on a journey to familiarize myself with TypeScript, I undertook a straightforward program by bundling all my .ts files using Browserify for browser compatibility.

Picture a basic variable declaration in TypeScript:

main.ts
let testVar = "Something";

Here's the content of my gulpfile.js for compilation and bundling purposes:

'use strict';

var gulp = require('gulp');
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var minify = require('gulp-minify');


gulp.task('build',['minify'], function () {

    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
        cache: {},
        packageCache: {}
    })
        .plugin(tsify)
        .bundle()
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest("dist"));

});

gulp.task('minify',function () {
    gulp.src('dist/main.js')
        .pipe(minify({
            ext:{
                src:'.js',
                min:'.min.js'
            },
            ignoreFiles: ['.min.js']
        }))
        .pipe(gulp.dest('dist'));
});

As for my tsconfig.json:

{
  "compilerOptions": {
    "module": "system",
    "sourceMap": true,
    "lib": ["dom", "es2015.promise", "es5"],
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/**/*"
  ],
  "files": [
    "src/**/*"
  ]
}

The build task functions smoothly, and the TypeScript code operates as intended. However, upon including the compiled and bundled code in my .html file and attempting to access the testVar variable by simply calling it in the Chrome console using console.log(testVar);, an error is returned:

Uncaught ReferenceError: testVar is not defined

Below is the compiled + bundled .js file:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
let testVar = "Something";
},{}]},{},[1])

//# sourceMappingURL=main.js.map

How can I access the functions and variables within the bundled .js file? What approach should I follow to design the API of my library in TypeScript? (any recommended resources)

Answer №1

If you want your code to function properly, make sure to include the standalone option in your Browserify configuration.

Here is an example of how your Browserify task should look like in Gulp:

 return browserify({
        standalone: "myLibrary",
        basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
        cache: {},
        packageCache: {},
    })

Note the use of standalone: "myLibrary".


Next, ensure that you are exporting something in your main.ts file, for instance:

//main.ts
export function greetUser(name:string){
 console.log("Hello, " + name);
}

Afterwards, execute your gulp build task (which will compile and browserify/bundle your TypeScript files), insert the bundled script into your webpage, launch Chrome console (F12), and then type the specified name of your standalone object defined in your browserify task (in this case it was named as myLibrary).

To see the response in our scenario, just enter this command in the console:

myLibrary.greetUser("John");

Answer №2

Can anyone suggest a good resource for designing the API of a TypeScript library?

This question is primarily related to setting up a build tool chain. Depending on your preferences, using a tool like webpack can be very beneficial. Below is an example configuration:

module.exports = {
    /** Specify the entry point for the built js file */
    entry: {
      myLibrary: './lib/index.js',
    },
    output: {
        filename: './umd/myLibrary.js',
        libraryTarget: 'umd',
        /** Define the library name within the global scope */
        library: 'myLibrary'
    }
};

Check out the MyLibrary project on GitHub for more insights.

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

Obtain the Key with the Greatest Value from a JSON Object

I'm currently working with data fetched from an API response in an attempt to identify the pitch with the highest speed. Below is a snippet from the API response. { page: 1, total_pages: 4, listings: [ { name: "Zack Greinke", pitc ...

Merge arrays with identical names within the same object into one cohesive object containing all elements

I just started using Vue and I'm not entirely sure if it's possible to achieve what I have in mind. Here is the structure I have: { "items":[ { "total":1287, "currency":"USD", "name":"string", "itemID":"", "pro ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...

Tips for sending information to a modal dialog box

My menu is dynamically generated with menu items using a foreach loop. Each item includes an event name and an edit button tailored to that specific event. Check out the code snippet responsible for creating this menu: foreach ($result as $row) { $eventid ...

Applying custom CSS to individual divs based on their text height using jQuery

I have a grid consisting of multiple boxes each sized at 280px by 280px, and I am seeking a way to vertically align text within hover overlays on each box. While my current code successfully aligns the text for the first box, I am encountering issues due ...

What is the best way to retrieve the outcomes of .query within a class?

Currently, I am working on a NodeJS application using coffee script. My objective is to save the results of a sql query executed by a class into a variable that can be returned by that same class. This is what I have so far: class dataBase mySQL = requ ...

Determining the meeting time of two objects in motion with varying angles

I am faced with a scenario where two objects are moving at different angles, and I need to determine when they will meet. The goal is to calculate the meeting time of these objects, with the return type being a time value or "infinite" if they will never m ...

The battle of Any, Generic Type, and Unknown in Typescript

Is it advisable to replace the type any with Generic Types? I understand that using type any is generally discouraged as it removes type checking in TypeScript, making it unsafe. So what is a better alternative - using unknown or generic types? For examp ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Using jQuery plugins in JavaScript files

I was curious about how to properly import jQuery libraries after installing them from npm. I tried the following methods, but encountered an error: import countdown from 'jquery.countdown'; $.countdown = countdown; $("#hours1").countdown("2020 ...

Using Ajax Uploader multiple times in a single page

I created a custom ajax file uploader that functions perfectly with one instance on the page. However, I am currently facing an issue while trying to modify it to support multiple instances. When I attempt to upload multiple files using one form, the first ...

Is there a way to retrieve the directory path of a folder that a user selects using a file input, without the need for them to actually upload the contents of the folder?

Is there a way to retrieve the selected folder path from the user without having them upload the files inside the folder? My goal is for the user to specify the location where they want to save the file that I will supply. I am looking to only display th ...

Why does it say "not exist" when I write const in my .d.ts file?

Hello, I have a question. When I declare a global variable using const like this: import { PrismaClient } from "@prisma/client"; declare global { namespace globalThis { const prismadb: PrismaClient; } } I encounter an error that says: ...

Trouble arises when attempting to categorize an array of objects in JavaScript

My array consists of various objects: [{id: 1, name: 'Apple', category: 'Fruit'} {id: 2, name: 'Melon', category: 'Fruit'} {id: 3, name: 'iPhone', category: 'Phone'} {id: 4, name: 'Samsung Ga ...

Is there a way to increase the row size only when it is clicked on?

I am facing an issue with my material-ui table. Whenever I click the button to expand row1, it also expands the second row simultaneously. How can I resolve this so that only the specific row I click on expands? <Table stickyHeader aria-label="st ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Error encountered when generating bower.json due to absence of version number

After generating the bower.json file, I noticed that the version number was not included in the information collected. The current content is as follows: { "Name": "conFusion", "Authors": [ "Aurora" ], ... } Although the version n ...

I am attempting to create an API request that is dependent on the outcome of another API request by utilizing a forEach loop. Is there a different approach I could take to achieve the desired

After successfully implementing an API request based on the result of another API request, I am looking for a more efficient method than using forEach for my subsequent API call. Is there a way to achieve this by utilizing Promise.all or any other alternat ...