A guide on importing JavaScript modules into TypeScript

I am curious about how to import a JavaScript module in TypeScript.

Project

  1. The module is "amd."
  2. Utilize the outFile option for a single file.
  3. Manage internal modules using ///<reference path=''/>

Code

app.js

export function func(a, b) {
    return a+b;
}

MainApp.ts

import Stats from "../app";    

class MainApp {

    foo() {
        const f = func(1, 2); // not defined (runtime error)
    }
}

Error

SyntaxError: Unexpected token export
ReferenceError: define is not defined
Main.js:6667
    at d:\...\Main.js:6667:2
ReferenceError: MainApp is not defined
    at window.onload (d:\...\index.html:18:24)

Define not found.

Answer №1

There may be an issue with default exports. Check out this example tailored to fit your code structure:

tsconfig.json:

{
    "compilerOptions": {
        "strict": true,
        "allowJs": true,

        "target": "es6",
        "module": "commonjs"
    }
}

app.js:

export function calculateProduct(a, b) {
    return a * b;
}

MainApp.ts:

import {calculateProduct} from './app';

class MainApp {
    bar() {
        const x = 3;
        const y = 4;

        const result = calculateProduct(3, 4);
    }
}

global.d.ts:

declare module '*.js';

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

Ways to prevent a single element from being included in the selection of the entire

Here is my question: I am facing an issue with a context menu that should only disappear when clicking outside of a specific row within that menu. The element I want to exclude, with the id "except", is buried deep within multiple parent elements in my co ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Add a JavaScript library to the header directly from the body of a webpage, ensuring it is exclusive to a single

I am using the Google Charts JS library on a single page within my project, with external and global headers and footers. The head tags are located in a head.php file, where all required JS libraries are included. The structure of my pages is as follows: ...

`How can a timer be removed from memory?`

Does the memory allocated for timers set using window.setTimeout get deleted immediately after the callback function completes its execution? ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

What are the installation steps for the npm package (math-simple-integrals)?

Hello, I've been attempting to set up the npm package called 'math-simple-integral' but am encountering some difficulties making it function properly. Initially, I utilized math.js and simply included the CDNJS script src <script src ...

Various designations for varying entities of identical category

I want to update an array of objects with a type 'person' to have unique identifiers like 'person0', 'person1', and so on. Currently, the setup looks like this: var population = []; var populationCount = 0; function person(i ...

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function. calculeSalaire() { this.fraisGestion = this.getFraisGestion(); this.tauxFraisGestion = this.getTauxFraisGestion(); this.salaireBrut = this.getSalaireBrut(); this.salaireNet = this.g ...

What can Yeoman do with php files?

How can I set up Yeoman (latest version: v0.9.6) to serve php files? I came across this post but couldn't get it to work. I installed https://github.com/fgnass/gateway, https://github.com/fgnass/tamper and made the necessary updates to Yeoman accor ...

Issue encountered when attempting to store the initial element in the todo array

I am facing an issue with my basic todo application in React using react-hooks. Whenever I try to take my inputValue and assign it to an object to save it in my items array, it doesn't seem to work. The first assignment after the onSubmit action res ...

Arranging users based on their highest number of followers in Meteor

Welcome to my Meteor project! I'm currently working with two collections: 1 - followers "_id": "_id", "follower": "username1", "following": "username2" } 2- users "_id": "_id", "username": "username", [...] } I am looking to sort users b ...

A comprehensive guide on effectively utilizing a lookup table in a shader using three.js

I have developed a basic three.js project that involves using a height map. Below is the specific code snippet responsible for creating the shader material: function loadHeightMap() { // setting up a mock lookup table var lut = []; for ( var n ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

Unable to successfully export ExpressJS routes to an external file when targeting the root path

I am seeking a way to organize my routes by exporting them into external files. Currently, all routes except the root route are functioning correctly: localhost/login -> "Login page" localhost/ -> empty server.js: // SERVER SETUP ============= v ...

eliminate element from formBuilder

When I execute formBuild.group, I am creating two temporary values for validation purposes only. These values are not intended to be saved in the database, so I need to remove them before saving. profile.component.ts: profileForm: FormGroup; constructor ...

Utilizing jQuery arrays to dynamically insert values into ChartJS

I am currently facing a challenge in dynamically populating a pie chart in ChartJS with data retrieved through a jQuery/AJAX query. The issue lies in formatting the data in a way that is compatible with ChartJS. The required format is as follows: var dyn ...