The paths required are not correct following the transpilation of a TypeScript file using Babel

Issue

Every time I use nodemon with npm run start, I encounter the error message "Error: Cannot find module 'Test'". Similarly, when I build files using npm run build and try to run ./dist/index.js, I face the same issue.

It seems that the require path in ./dist/index.js is not being recognized correctly.

I am unsure about which configuration settings need to be adjusted, so I am reaching out for assistance.

If you have dealt with a similar problem before, I would greatly appreciate it if you could share your solutions with me. Thank you!

Code Snippets

./src/index.ts

import Test from 'Test';

const test = new Test();

./src/Test/index.ts

export default class Test {
    constructor () {
        console.log('Test');
    }
}

./dist/index.js

"use strict";

var _Test = _interopRequireDefault(require("Test"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var test = new _Test.default();

./package.json

{
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "babel ./src --extensions .ts,.js --out-dir ./dist",
    "start": "nodemon ./src --exec babel-node --extensions .ts,.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.0.0-beta.47",
    "@babel/core": "^7.0.0-beta.47",
    "@babel/node": "^7.0.0-beta.47",
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.47",
    "@babel/plugin-proposal-object-rest-spread": "^7.0.0-beta.47",
    "@babel/polyfill": "^7.0.0-beta.47",
    "@babel/preset-env": "^7.0.0-beta.47",
    "@babel/preset-typescript": "^7.0.0-beta.47",
    "cross-env": "^5.1.5",
    "nodemon": "^1.17.4"
  }
}

./tsconfig.json

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "experimentalDecorators": true,
        "forceConsistentCasingInFileNames": true,
        "lib": ["ES2015", "ES2017", "DOM"],
        "noEmit": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "module": "esnext",
        "moduleResolution": "node",
        "paths": { "*":["node_modules/*", "src/*"] },
        "pretty": true,
        "strictNullChecks": true,
        "target": "es5",
        "typeRoots": ["./node_modules/@types"]
    }
}

./.babelrc

{
    presets: ['@babel/preset-env', '@babel/preset-typescript'],
    plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-object-rest-spread']
}

Answer №1

To properly import the module Test in your TypeScript file, make sure to use the relative path import Test from './Test'; instead of just import Test. This way, TypeScript will be able to locate the local module within your project structure.

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

What methods are available to fill a canvas with shapes other than circles?

My goal is to fill the canvas with a black color. The code I have used for this purpose is as follows: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.fillStyle='rgba(0,0,0,0.1)'; ctx.fillRect(0,0,c.width,c.height) ...

Retrieving dropdown options with the help of selenium and node.js

I'm looking to gather all the options from a dropdown menu and loop through them to submit a form. I need the list of values from the dropdown. The following Java code meets my requirements perfectly, but I am in need of the same functionality in Jav ...

navigating directly to a particular slide within a Bootstrap carousel on a different page by clicking

Attempting to set up a bootstrap build, where clicking on certain states on one page will direct the user to a specific slide on another page. I'm struggling to grasp this concept. A friend of mine, who is a Javascript developer, provided some code f ...

After updating to the latest npm version, the NodeJS server continues to display the error message "Upgrade Required" when loading pages

After developing a Node project using NodeJS version 5.4.x and NPM version 3.3.12 on Windows, I encountered an issue where the project throws an "Upgrade Required" message (HTTP Error code - 426) upon loading the page after some time of inactivity. To add ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

The function for executing the specific command is not recognized and is resulting in a TypeError: client.commands

I'm having an issue with the code below and need a solution. Please help. Error : TypeError: client.commands.get(…).execute is not a function I am encountering difficulty with this specific command in my code: client.command ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

The Ajax request keeps encountering a bad request error despite it working perfectly fine in Postman

After spending hours conducting extensive research and trying various methods without success, I am still unable to obtain a JWT token after providing the user and password. function listenForLogin() { console.log('listening') $('# ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

Enable CORS for AJAX requests with RESTful web services in Google Chrome

My web-based project is fully written in jQuery and JavaScript. On the client side, I am calling RESTful webservices via AJAX like this: $.ajax({ type: 'GET', timeout: 1000000000, headers: { 'Access-Control-Allow-Origin': ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

What causes the empty gap to appear during animated transitions between two 'div' elements?

Is there a way to eliminate the white space in between elements during animation? Should I wrap both divs into another div to achieve this? I am using position-top to adjust my div animations. Could this be causing the issue? What other methods can you s ...

li experiencing a background width problem due to extended text

Check out this code snippet with a problem In the image below, you can see that the background of the li element with more text is larger compared to the others. It's important to note that the <ul> is scrollable. I've experimented with va ...

What does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Retrieving an object from an ObservableArray in a Nativescript application

Within my service class, I have an array of quests defined in the following manner: import { ObservableArray, ChangedData } from 'tns-core-modules/data/observable-array/observable-array'; quests: ObservableArray<Quest>; To add quests to ...

There is an issue with Node/Express not accurately updating the data model

I recently went through a tutorial on creating a RESTful API with Node.js and MongoDB. While it worked well overall, I encountered a few issues. My Player model is as follows: var player = new mongoose.Schema({ name: String, email: String, score: String } ...

The elusive Yeoman composeWith module remains elusive and cannot be found

Feeling stuck on a coding problem. I've created a generator that contains other generators. When I install it from my local copy using npm link, composeWith works perfectly. But when I install the generator from GitHub, I encounter an error stating " ...