Is there a way to exclude the file type as .js when saving a file in .ts format?

I am working on importing .ts files as they are without specifying the file type as .js, for example:

import {acccessRights} from "utils/accessRights"
.

My desired outcome is to be able to import a method from another file without having to specify the file type.

However, when I try to do this, I encounter an error message:

GET http://127.0.0.1:5501/build/lights/switchLights net::ERR_ABORTED 404 (Not Found)
.

As a temporary solution, I have resorted to specifying the file type as .js like this:

import { switchLights } from "lights/switchLights.js"
. But this workaround causes issues with jest because it cannot locate the .js file.

This snippet shows part of the index.html file:

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

And here is part of the app.ts file:

import { User } from "./utils/accessRights";
import { switchLights } from "./lights/switchLights";

In the utils/accessRights.ts file, we define the interface and function like so:

export interface User {
  role: string;
}

export function userIsAdmin(user: User): boolean {
  return user.role === "admin";
}

The lights/switchLights.ts file contains the following code:

import {User, userIsAdmin} from "../utils/accessRights";

let lightsCondition: boolean = false;

function switchLightsRender() {
  document.getElementById("lightsCondition").innerHTML = lightsCondition ? "ON" : "OFF";;
  document.getElementById("lightsButton").innerHTML = `Lights ${!lightsCondition ? "ON" : "OFF"}`;
}

export function switchLights(user: User) {
  if (!userIsAdmin(user)) return false;
  lightsCondition = !lightsCondition;
  switchLightsRender();
  return true;
}

Here are the Jest test files for reference:

The test/utils/accessRights.test.ts file:

import {userIsAdmin, User} from "../../src/utils/accessRights";

export let userTest: User = { role: "admin" }

test('user is admin', () => {
  expect(userIsAdmin(userTest)).toBe(true);
})

And the test/lights/switchLights.ts file:

import {userTest} from "../utils/accessRights.test";
import {switchLights} from "../../src/lights/switchLights";

test("lights switched ON/OFF", () => {
  let lightsConditionRef = document.createElement("span");
  lightsConditionRef.setAttribute("id","lightsCondition");
  document.body.appendChild(lightsConditionRef);

  let lightsButtonRef = document.createElement("button")
  lightsButtonRef.setAttribute("id","lightsButton");
  document.body.appendChild(lightsButtonRef);
  
  expect(switchLights(userTest)).toBe(true);
})

Next, here is one of the transpiled .ts files to a .js file with an issue in the import statement:

Expected result:

import { userIsAdmin } from "../utils/accessRights.js";

Actual result:

import { userIsAdmin } from "../utils/accessRights";

This is the auto-generated build/lights/switchLight.js file:

import { userIsAdmin } from "../utils/accessRights";
var lightsCondition = false;
function switchLightsRender() {
    var lightsConditionRef = document.getElementById("lightsCondition");
    if (lightsConditionRef !== null)
        lightsConditionRef.innerHTML = lightsCondition ? "ON" : "OFF";
    ;
    var lightsButtonRef = document.getElementById("lightsButton");
    if (lightsButtonRef !== null)
        lightsButtonRef.innerHTML = "Lights " + (!lightsCondition ? "ON" : "OFF");
}
export function switchLights(user) {
    if (!userIsAdmin(user))
        return false;
    lightsCondition = !lightsCondition;
    switchLightsRender();
    return true;
}

Answer №1

Here is the problem you are facing: How to create valid ES6 module import statements using TypeScript?

Solution:

To resolve this, consider using a bundler. I recommend trying out Parcel, as it requires minimal setup.

If your requirements are more complex and involve specific scenarios, you can opt for Webpack.

Guide to Installing Parcel:

  1. npm i -D parcel
  2. Update the import in your HTML file from app.js to app.ts (or whatever name your file has).
  3. Add an npm script for development:
"scripts": {
  "serve": "parcel index.html"
},
  1. Execute npm run serve

By doing so, a server will be hosted for you (URL displayed in terminal) and any changes made will trigger recompilation.

Refer to the Parcel Documentation(Starting Guide) for more details.

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

Sequelize is encountering an issue where it is unable to read properties of undefined, resulting in a "TypeError: Cannot read properties of undefined (reading 'constructor')"

I encountered a problem with Sequelize and I'm struggling to pinpoint the exact source of the issue. The error message I'm receiving is: TypeError: Cannot read properties of undefined (reading 'constructor') and here is the stack trace: ...

Ways to extract the numerical values from user inputs and store them in an array using vanilla JavaScript

My goal is to extract and separate different numbers from an array as each number holds a unique significance. To achieve this, I am retrieving input values where the numbers are separated by spaces (" "), then attempting to split them so that each number ...

Is it possible to render conditional templates using props in Vue3?

I'm attempting to create a toggle button that opens a hamburger menu when clicked. I created the boolean property "clicked" in the file "App.vue", passed it down to "Navbar.vue", and now I want to be able to toggle the "clicked" property to either "t ...

Another option for handling a series of conditional statements instead of a bulky

Can someone help me with a coding issue I'm facing? I have an application that contains a large number of buttons which I need to trigger using keyboard presses. Currently, I am using a switch statement for this purpose. However, as the number of butt ...

Using Wordpress and JavaScript to dynamically hide a button if a product in the online store does not have an SKU

I'm encountering an issue on my Wordpress site where products with variations are not displaying the inner text on a certain element, despite the fact that the text is present when I inspect the element. Here's the code: const makerBtn = document ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

The content is not able to be shown within a frame due to the 'X-Frame-Options' being set to DENY during the Facebook fb.ui share method

Encountering this message in the console: Refused to display in a frame due to 'X-Frame-Options' set to DENY This issue arises when the website is displayed in its mobile version, which involves a distinct set of HTML and assets provided if the ...

Creating a simulated class within a function utilizing Jest

Currently, I am in the process of testing a controller that utilizes a class which functions like a Model. const getAllProductInfo = (request, response) => { const productInformation = new ProductModel().getAll(); response.status(200) resp ...

Dynamic Bootstrap Modal for Enhanced User Experience

We have been racking our brains over this issue. Whenever the Bootstrap modal is opened, it shifts the background of the page to the top and then returns it back when closed. Is there any way to prevent this movement? So far, we have updated to Bootstra ...

WebdriverIO and Cucumber: Make sure the promise resolves in under 10 seconds for function timeout

Currently, I am working on developing an application that involves a series of page navigations for users to complete information. To facilitate navigation to specific parts of the page, I attempted to create a generic step definition as a "background" ste ...

A versatile function that can process any data type without losing its structural details

Is it possible to create a function that accepts any type as an argument while still retaining the original type information of the input? const preserveType = (input: any) => input // using 'any' for flexibility const data = { foo: ' ...

CodeForge - A major issue with excessively lengthy words resulting in an incorrect solution on assessment 1, but successful execution on my personal computer

Can someone help me understand, why Codeforces is showing an error while the code runs perfectly on my PC? Any assistance in solving this issue would be appreciated. I have included the complete code snippet below for reference. I have also updated it ...

Creating a Form with a Custom Format in AngularJS

Just starting out with AngularJS and currently working with ACTIVITI. I'm looking to create a form in a specific structure where each response follows this format: { "taskId" : "5", "properties" : [ { "id" : "room", ...

Using Typescript to customize component props and theming through CSS Modules

Currently, I am in the process of building a react component library using typescript and CSS Modules to simplify the project. However, I am facing challenges with typescript interfaces, especially when it comes to theming variants for my components. For ...

The term 'App' is being referenced as a value when it is intended to be a type. Perhaps you meant 'typeof App'?

I am eager to master Typescript with React through hands-on experience, so I recently made the manual transition from JavaScript to TypeScript in my create-react-app. However, when working with my default testing file App.test.ts: import { render, screen ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

Embed an interactive HTML template within an iframe source using JavaScript

My current task involves dynamically retrieving an HTML template on the fly. I am wondering how I can append this HTML code to an iframe's src attribute. I sought advice from others in the community and was able to create a working jsFiddle for a sim ...

Load different fonts dynamically based on environment configuration

My question is regarding loading multiple fonts from a font.css file in React. I need to make the font path dynamic based on the environment variables. Can anyone suggest a solution for achieving this? I've attempted to create a font.scss file and de ...

Authorization in Confluence REST API

Currently, a user is logged in to Confluence; There is an external web application that saves attachments to a specific page. In order to make REST calls from the external app, I need the user's credentials for Confluence (which I do not have because ...