Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture

However, I'm facing an issue with the import/export functionality when running this command:

tsc && babel build-ts -d lib && webpack --config webpack.config.js

ERROR in ./lib/index.js Module not found: Error: Can't resolve 'index' in 'C:\Users\aurel\Desktop\Platformer\lib'

ERROR in ./lib/index.js Module not found: Error: Can't resolve 'file' in 'C:\Users\aurel\Desktop\Platformer\lib'

index.html :

<script src="dist/bundle.js"></script>

index.ts

export const index = "test";
import { file } from 'file';

console.log(file)

file.ts

export const file = "test";
import { index } from 'index';

console.log(index)

webpack.config.js

const glob = require("glob");

module.exports = {
   entry: {
   js: glob.sync("./lib/**/*.js"),  
},
output: {
  filename: 'bundle.js',
  path: __dirname + '/dist',
},
};

tsconfig.json

"target": "es6",
"module": "amd",
"outDir": "./build-ts",

Any ideas on how to solve this issue? I would appreciate any help, thank you in advance!

Answer №1

It is important to use relative imports instead of absolute ones:

export const username = "john_doe";
import { profile } from './profile';

console.log(profile)
export const profile = "John Doe's Profile";
import { username } from './username';

console.log(username)

By using relative imports, the file will be searched for within the project directories, rather than in node_modules.

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

Is it possible to write TypeScript and execute it directly with Node?

I am attempting to write some basic typescripts but I am encountering an issue with the setup below: node src/getExchangeAndTickerList.ts import * as mkdirp from 'mkdirp'; ^^^^^^ SyntaxError: Cannot use import statement outside a module ...

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

There was an error in calling `prisma.user.findUnique()`:

Here is my code snippet for the API route: export const POST = async (req: NextRequest) => { ... try { const { email, name, password } = await req.json(); console.info(email, name, password); const existingUser = await prismadb.user.findUn ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

What is the best way to provide inputs to a personalized validation function?

I am seeking a solution to pass an array of prefix strings to my custom validator in order to validate that the value begins with one of the specified prefixes. Below is the code snippet for my current validator: @ValidatorConstraint({ name: 'prefixVa ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

Angular 12's BehaviorSubject should have been empty object array, but it unexpectedly returns undefined

Exploring different scenarios with a livesearch functionality: No user input (observable = undefined) No results found (observable = empty array) Results found (observable = non-empty array) The issue lies in how my behavior subject interprets an empty a ...

Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true. users = [ { name: 'ali', male: true, valid: ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...

Employing Multer and Express in conjunction with TypeScript

Overview Currently, I am working on a project that involves creating a user-friendly website where individuals can easily upload images. For this particular task, I have employed Node.js, React, Multer, and Typescript. Issue at Hand app.post('/admi ...

Retrieve a collection of nested dictionaries containing flask and angular data

In my app development journey with flask and ionic(angular), I'm working on returning a JSON list. Here's the python code snippet: def get-stocks(): # Select all stocks cursor.execute("""SELECT * FROM `tbl_symbol_index`"" ...

"What sets apart the usage of `import * as Button` from `import {Button}`

As a newcomer to Typescript, I am facing an issue while trying to import a react-bootstrap Button. In scenario 1: import {Button} from 'react-bootstrap/lib/Button' In scenario 2: import * as Button from 'react-bootstrap/lib/Button' B ...

Guide to adding information to a table with the help of an "interface" in Angular 6 and utilizing Typescript

Looking for some guidance with Angular as I am just starting out. I am currently trying to send an API request in angular 6 using Typescript. However, I am facing difficulties when it comes to adding data to a table. Check out my code on: Codepen In my p ...

Error: Uncaught TypeError - The function boss.SetBelongToClan is not defined

Currently, I am faced with an issue while working on a typescript and sequelize project within an express application. The problem arises when trying to create a type-safe interface for utilizing the associate function. Within my Instance interface, there ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

Associating function parameters with object types in TypeScript

In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as: type result = { GE ...