What is the process for importing a TypeScript file as a library?

My customized personal "library," dubbed methlib and saved as a .ts file on my computer, contains a plethora of classes, interfaces, functions, and more that I frequently use and prefer to keep in one convenient location. The dilemma I face now is how to utilize these functions and elements in another TypeScript project I'm working on (as one typically would with a library). In the past, before converting it to TypeScript, I could easily include it in the HTML file by directly referencing the local file in my main web directory, enabling any changes to take immediate effect. However, now that I've transitioned to TypeScript, I find myself at a loss. As a newcomer to TypeScript and advanced JavaScript and web development terminologies, I struggle to grasp the concept.

import { Collider } from "Methlib/methlib"

Despite my webpack configuration (largely borrowed from a template and not fully comprehended) structured as follows

const path = require('path');
module.exports = {
    entry: "./src/script.ts",
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, 'dist')
    },
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".js"],
        alias: {
            Methlib: "./../Methlib-js/"
        }
    },
    module: {
        rules: [{ test: /\.ts$/, loader: "ts-loader" }]
    }
}

accompanied by a file layout:

<root>
 | Methlib-js
 | | methlib.ts
 | <project folder>
 | | node_modules
 | | src
 | | | script.ts
 | | webpack.config.js
 | | package.json
 | | package-lock.json

Upon executing >node_modules\.bin\webpack, I encounter an error:

ERROR in <root>\<project folder>\src\script.ts
./src/script.ts
[tsl] ERROR in <root>\<project folder>\src\script.ts(5,26)
      TS2307: Cannot find module 'Methlib/methlib' or its corresponding type declarations.

Please respect the usage of <root> and <project folder> as placeholders to conceal my exact file structure when it's not essential. It's important to note that <root> is not a component of the project but simply signifies the root of my file hierarchy.

Answer №1

Make sure to define the path mapping for TypeScript in the configuration:

{
  "compilerOptions": {
    "baseUrl": ".", // It is necessary when using "paths".
    "paths": {
      "Methlib": ["../Methlib-js/methlib.ts"] // This mapping is relative to the "baseUrl"
    }
  }
}

Check out the REPL on Repl.it

Answer №2

After careful investigation, it was found that providing the complete absolute path to the library in the webpack.config.js file resolved the issue. Surprisingly, additional testing revealed that there is no need to include the path mapping in the tsconfig.json file as well.

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

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop? An example of an array-like object would be: let elements = document.querySelector('#someid').children ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

Unable to Add Dependency to Subclassed Object

In my setup, there are three classes that interact with each other. I am utilizing inversify for handling dependency injection. However, I encountered an issue when I injected the class MessageBroker into the derived class Repository and found that the Mes ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

Challenges Encountered When Inputting Year in ReactJS Date Picker Component

I've encountered a problem with a date input component in my ReactJS project and need some assistance with resolving two issues: Problem 1: Year Input Length The first issue is that the year input field allows six digits, but I want to restrict it to ...

What is the method for allowing tooltips to disappear when clicked on?

Is there a way to prevent a tooltip from hiding unless it is clicked on? Would using a popover be a better solution? var Button = document.querySelector('.Button'); $(Button).attr("data-toggle", "tooltip"); $(Button).attr("data-placement", "top ...

Is there a way to show the text within a div tag in a tooltip without relying on jQuery?

Is there a way to display the text content of an HTML element inside a tooltip? I am struggling to achieve this, as I would like to have the word test appear in the tooltip, but it's not working. Unfortunately, we are not using jQuery in our code bas ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

Uploading Images to Cloudinary in a MERN Stack: A Step-by-Step Guide

I am facing an issue while trying to store company details, including a company logo, in Mongo DB. I am attempting to upload the image to Cloudinary and then save the URL in Mongo DB along with other details. Currently, my code is not functioning as expec ...

What is the best way to connect an HTML file to a controller in Angular.js?

When developing an app module using the MEAN stack with MVC, I created a folder named AppModules. Inside AppModules, there is a folder called search, which contains three subfolders: models, views, and controllers. I've written an HTML file in the vie ...

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

React client side componentDidMount function encountering issues (server side rendering)

Greetings to the Stackoverflow community Apologies in advance if my explanation is not clear enough When a user directly types a URL, the server makes a request, fetches the corresponding data, and renders it on the screen flawlessly. However, when a us ...

Is it possible to remove the active class when clicking on an active link for a second time

While navigating the web, I stumbled upon a question about adding an active link to the currently clicked menu item. The suggested solution was to implement the following code: $("a").click(function(){ $("a").removeClass("active"); $(this).addCla ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

issue with the submit button due to non-functional base64 encoded image

After successfully converting multiple file images to base64 format, I encountered an issue when trying to submit the values. When a user selects multiple images and clicks the submit button, the converted base64 values are returned as undefined. How can t ...

What is the best method to change the value of a nearby TD text box?

I am currently developing a shopping cart application that requires me to update product screens based on users' previous orders stored as local JSON data. The product screen is built using JSON returned from the server. My goal now is to automatical ...