Webpack is unable to properly parse TypeScript files, resulting in a module parse error that states: "Unexpected token

While working on an old project, I decided to set up Typescript and Webpack. However, I ran into a sudden error:

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

So, I created a new project from scratch with the following setup:

webpack.config.js

const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
    entry: {
        main: './src/index.ts'
    },
    module: {
        rules: [
            {
                test: '/\.ts$',
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',
                            '@babel/preset-typescript'
                        ]
                    }
                },
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.ts'],
    },
    plugins: [
        new webpack.CleanPlugin(),
    ],
    output: {
        filename: '[name].[contenthash].js',
        path: path.join(__dirname, 'dist')
    },

}

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./",
        "rootDir": "src",
        "outDir": "dist",
        "lib": ["ES6", "DOM"],
        "target": "es5",
        "module": "es6",
        "noImplicitAny": true,
        "removeComments": true
    }
}

src/index.ts (sourced from here)

class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
greeter.greet();

Surprisingly, I encountered the same error again :/

ERROR in ./src/index.ts 2:12 Module parse failed: Unexpected token (2:12) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

I feel like I'm missing something crucial here. Any idea what it could be?

ps: I also tried using different loaders like ts-loader and awesome-typescript-loader.

Your help is highly appreciated! Thanks in advance!

Answer №1

The main issue here is that your Typescript rule is not correctly matching ("currently no loaders are configured to process this file"), causing Webpack to interpret your TS files as Javascript and encountering an error with the TypeScript-specific : on line 2 character 12. Looking at your webpack.config.js:

test: '/\.ts$',

This needs to be a regular expression. Make sure to remove the single quotes:

test: /\.ts$/,

Refer to the Webpack documentation for more information on Rule.test and Condition.

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

Error in React.js: Attempted to register component with a target container that does not exist in the DOM

Hey there, I'm facing an issue that says: main.js:808 Uncaught Error: _registerComponent(...): Target container is not a DOM element. I checked out this question, but I can't seem to pinpoint what exactly I'm doing wrong. Below is the cod ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

Tips for improving the readability of my code

This code snippet pertains to handling a POST request in Express.js with MongoDB integration. router.post('/', function(req, res){ var data = req.body; Tag.find({name: data.name}).limit(1).exec( function(err, result){ if(err) { // ...

"Performing a row count retrieval after updating records in a Microsoft SQL Server database

Recently, I have been utilizing the MSSQL NodeJS package (https://npmjs.org/package/mssql#cfg-node-tds) in order to establish a connection with a MS SQL database and execute UPDATE queries. One thing that has caught my attention is that when an UPDATE que ...

What is the best way to align an HTML block (<ul>) immediately below an <input> using jQuery?

Here is the HTML code snippet: <html> <body> <div id="pgContent"> <div id="studyOverlay"> <div id="studyContainer"> <div id="studyTest"> ...

Is it possible to retrieve the throughput or latency data of a WebRTC stream directly from an RTCPeerConnection object?

Does anyone have suggestions on how to calculate the latency or throughput of a receiving stream in WebRTC? I'm familiar with using getStats(), but can't find a straightforward method. Any tips are appreciated! ...

What steps can I take to decrease the padding of this footer?

Is there a way to reduce the height of the footer so it doesn't dominate the screen on both large and small devices? https://i.sstatic.net/nIQz6.png import { Container, Box, Grid } from "@material-ui/core"; const Footer = (props) => { ...

ReactJs - Reactstrap | Issue with Jumbotron displaying background color

I am trying to create a gray background using Jumbotron in reactstrap. After installation and reference in required places - index.js import 'bootstrap/dist/css/bootstrap.css'; Jumbotron has been implemented in SignIn.js - import Re ...

Trouble arises when trying to create an auto suggest text box using PHP and Javascript

I've been working on creating a basic auto-suggest input feature that connects to a MySql database to retrieve data. However, I'm facing a particular issue where when I enter the name of an object that I know exists in the database, the input bar ...

Storing user input from a dynamic form into a database using Kendo UI

I've successfully populated dynamic input form fields. However, I'm unsure how to save the data into a database using a put/post API since I have only used a get API so far. HTML code <div id="renderform" class="form horizontal-for ...

React - what propType should be used for the Material UI icon?

I am planning to send a Material-UI icon to the Test component and I need to define the correct proptype for it. App.js import "./styles.css"; import VisibilityIcon from "@material-ui/icons/Visibility"; import Test from "./Test&q ...

The error message "TypeError: Cannot access 'url' property of undefined in Strapi

I am facing an issue with a list of items where some have download links while others do not. Whenever I try to render an undefined URL, it triggers an error. To resolve this, I attempted the following: if (spectacle.pdf.url) { const pdf = spectacle.p ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

best method for integrating google maps on a website

I want to optimize the loading speed of Google Maps v3 on my website. Here is my current setup: In a .js file at the end: google.maps.event.addDomListener(window, 'load', initialize); And at the end of the HTML page code: <script type="te ...

Error: When trying to run npm start in a React project, an issue arises where the property 'prototype' is undefined and results in

Having trouble while running my react app, I am encountering an issue. Can someone please assist me with this? A TypeError is showing up: "Cannot read property 'prototype' of undefined". This error is displayed on the browser page. The terminal o ...

Concealing jQueryUI tooltip upon clicking a "target=_blank" link

I have implemented jQuery to display tooltips for all links on my webpage that include a 'details' attribute. $(function() { $tooltip = $(document).tooltip({ show: false, track: true, ...

What is the best way to integrate a jQuery Plugin into an Angular 5 application powered by TypeScript 2.8.1

I am trying to incorporate jQuery into my Angular 5 project using TypeScript 2.8.1. I attempted to follow Ervin Llojku's solution but it didn't work: First, install jquery via npm npm install --save jquery Next, install the jquery types npm i ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...