Encountered an issue with importing a TypeScript module

One issue I encountered is that when importing a module in an app.ts script, the '.js' extension is not included in the import line of the compiled js file.

In my app.ts file, I have

import {ModuleA} from './ModuleA'

After compilation, in the app.js file, the import line looks like this:

import {ModuleA} from './ModuleA';

When including it in the html file, I use:

<script type="module" src="app.js"></script>

Unfortunately, the browser cannot find the module 'ModuleA'.

The only way it works is when I import like so:

import {ModuleA} from './ModuleA.js'

However, my goal is to import '.ts' module files, not '.js' module files.

I was hoping that the typescript compilation process would automatically add the '.js' extension to the import line.

Does anyone have any suggestions or solutions for this problem?

Answer №1

It appears that there is a bug in TypeScript. You can check out the issue at https://github.com/Microsoft/TypeScript/issues/13422.

Unfortunately, there is no fix currently being worked on. In the meantime, your current approach is correct.

import {ModuleA} from './ModuleA.js'

Answer №2

An alternative option is to utilize webpack for consolidating multiple JavaScript files into a single file, eliminating the need to include extensions.

Refer to the webpack guide for configuring typescript

Answer №3

When you neglect to define compiler options in the command line for tsc and lack a tsconfig.json file, typescript resorts to using default settings. As per the guidance provided in the typescript documentation, the defaults are set to es3 for the emitted language and commonjs as the module loader. Dissatisfied with these options, I opt to specify different configurations within a tsconfig.json file. Follow this setup for your project, which may initially feel like a significant effort but can be saved as a template, eliminating future repetition. This guide assumes that your machine is properly configured with npm.

To begin, create a new project in VS 2017, selecting ASP.NET Web Application (.NET Framework) as the template. Though unconventional, this choice results in a streamlined project void of unnecessary components. In the subsequent wizard page, opt for an Empty project, unchecking all boxes including authentication. Complete the wizard process.

At the root level of your project, add the following files:

package.json:

{
  "version": "1.0.0",
  "name": "asp.net",
  "author": "you",
  "private": true,
  "dependencies": {
    "core-js": "^2.5.3",
    "systemjs": "^0.21.0"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "module": "system",
    "target": "es5",
    "noImplicitAny": true,
    "noEmitOnError": true,
    "sourceMap": true
  },
  "files": [
    "app/app.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

system.config.js:

(function (global) {
  SystemJS.config({
    paths: {
      'npm:': '/node_modules/'
    },
    map: {
      app: '/app'
    },
    packages: {
      app: {
        main: 'app.js',
        defaultExtension: 'js'
      }
    }
  })
})(this);

index.html:

<!DOCTYPE html>
<html>
<head>
  <base href="/" />
  <meta charset="utf-8" />
  <title>Typescript with SystemJS and Modules Demo</title>
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/systemjs/dist/system.js"></script>
  <script src="system.config.js"></script>
  <script>
    SystemJS.import("app/app.js").catch(function (e) { console.log(e); });
  </script>
</head>
<body>
  <div id="personDiv"></div>
</body>
</html>

Additionally, create an app folder and include the following two files within it:

app.ts:

import { Person } from "./person";

export class App {
  constructor() {
    let person: Person = new Person();
    let div: HTMLDivElement = <HTMLDivElement>document.getElementById('personDiv');
    div.innerHTML = person.getName();
  }
}

// Use this assignment to start execution.
let a: App = new App();

// The following doesn't appear to work with SystemJS. It does with plain TypeScript.
// It is probably because SystemJS already defines a listener for window.onload,
// although I haven't verified that.
//window.onload = () => {
//  let a: App = new App();
//  let person = new Person();
//  alert(person.getName);
//}

person.ts:

export class Person {
  fullName: string;

  constructor() {
    this.fullName = "Test Guy";
  }

  getName():string {
    return this.fullName;
  }
}

After completing the setup, build and run the application to observe successful imports.

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

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

How can I expand and collapse all the Bootstrap panels simultaneously?

Is it possible to make all three panels collapse and expand simultaneously with just one button? <button data-toggle="collapse" data-target="#collapseOne-1,#collapseTwo-1,#collapseThree-1" ...></button> <div id="#collapseOne-1" class="coll ...

Meteor, app has been upgraded and now receiving error message 'TypeError: check is not defined'

I've been in the process of updating an old meteor project that was running on a version even older than 1.0.0. The issue cropped up at Meteor 1.4.2.3, but strangely another app is working smoothly on the same version. After making several adjustment ...

Looking to create a clone of an HTML element, make some modifications, and extract the HTML string without impacting the DOM?

After working with some HTML code, I encountered the following: <div style="background:red;width:900px;height:200px" id="wrap"> <div id="inner" style="width:300px;float:left"> ... </div> </div> The tasks at hand are ...

"jQuery's input type property is not functioning properly when attempting to append new

I am facing an issue with my dynamic table structure and the add row option. Whenever I click on add, a new row is created. However, the problem arises when the $("[name*=vehicle_type]").change(function () does not work for appended input fields. It only ...

Modifying the name of a file upload in AngularJS

Does anyone know a way to dynamically change the file name in AngularJS? <input type="file" onchange="angular.element(this).scope().filename(this)"> In the filename method, I am attempting to change the file name but the value is not updating. How ...

Sending data from multiple HTML table rows at once to a Django model

After a user selects items from a list, they can submit the selected items to be saved in a table. The table is dynamically rendered using JavaScript and the data comes from a Map with keys as primary keys and values as descriptions and prices. function d ...

Update a nested object key by concatenating key names with "." to create a string

Imagine having this specific object structure: var obj = { level1 :{ level2: { level3: { title: "champion" } } } } Now the goal is to update the title key using a provided string (note that it's a string, not an actua ...

"Can you tell me a way to identify variances between two dates displayed in a

I am looking to calculate the differences between two dates. I will input the date values in the text box and want the duration to be displayed in another text box. <script language=javascript> function formshowhide(id) { if (id == ...

Executing a JavaScript onclick event following the submission of a form

Within my HTML form, I have a radio button that triggers a JavaScript onclick function to disable certain text fields. However, after submitting the form, the disabled fields revert back to normal textboxes. To address this issue, I am looking for a way t ...

Tips for utilizing the if statement within ng-repeat in Angular version 1.0.8

My version of angular is 1.0.8-stable My main goal is to arrange data in rows of 3. This is the desired structure for my HTML: <div class="table-row"> <div class="item">item1</div> <div class="item">item2</div> ...

Tips on sorting through an array of subdocuments using two criteria in each subdocument

I am currently working on implementing a help request system that restricts the requester to submitting only one help request per topic to an expert. If the expert has multiple topics they can provide help with, I want to limit each requester to one help r ...

What's the best way to enable touch scrolling for items within a div container?

I am in the process of creating a code snippet that will allow users to scroll through items within a div, similar to a spinning wheel or slot machine. While I am aware of an existing solution for iPhone and iPod, I want to develop a simpler, more streamli ...

Having trouble getting the Html onload function to work in Google Sheets App Script?

I'm working with google sheets and I'm in the process of creating a document to track employees who are currently out of the office. I have added a menu option that allows me to remove employee data, which triggers the opening of a sidebar contai ...

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

Error in Syntax: Unforeseen symbol (Initial code)

Encountered Error: Unexpected token < Attempting to call a JavaScript function with console.log("hello world"); I am taking my initial steps into coding in Node.js without any frameworks, focusing on understanding the core and basic concepts of Node.j ...

New to JSON: Why is my variable returning as undefined?

Embarking on my first JSON project has brought some challenges that I am struggling to overcome. Here's the task at hand. I have created a basic scraper using Apify.com to extract data from a specific website. The data is presented in JSON format, an ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Generate several sliders using JQuery effortlessly

As I was attempting to create multiple sliders with JQuery in a more automated fashion using iteration, several questions arose (you can see a functional example below). Why does the first block of JQuery code work while the second block of JavaScript cod ...