Typescript not being transpiled by Webpack

As I set out to create a basic website, I opted to utilize webpack for packaging. TypeScript and SASS were my choice of tools due to their familiarity from daily use.

Following the documentation at https://webpack.js.org, I encountered issues with loaders like awesome-typescript-loader and ts-loader when incorporating ES6/TypeScript features in my code, such as type definitions and classes.

Transpiling my main.ts file resulted in the following error:

ERROR in ./src/app/main.ts
Module parse failed: Unexpected token (4:17)
You may need an appropriate loader to handle this file type.
| import { Slider } from './components/slider/slider.component';
|
| const contactForm: ContactForm = new ContactForm('#contact-form');
|
| const slider: Slider = new Slider('#slider-container', '.slide');

The contents of my main.ts:

import { ContactForm } from './components/contact-form/contact-form.component';
import { Slider } from './components/slider/slider.component';

const contactForm: ContactForm = new ContactForm('#contact-form');

const slider = new Slider('#slider-container', '.slide');

Presenting my slider.component.ts:

export class Slider {

  private container: HTMLElement;
  private slides: HTMLElement[];

  constructor(containerSelector: string, slidesSelector: string) {
    this.container = document.querySelector(containerSelector);
    this.slides = Array.from(document.querySelectorAll(slidesSelector));

    const containerWidth: number = this.slides
                                      .map(slide => slide.offsetWidth)
                                      .reduce((sum, offsetWidth) => sum + offsetWidth, 0);

    this.container.style.width = `${containerWidth}px`;
  }
}

Eliminating the types allowed successful transpilation of main.ts, but led to errors such as:

ERROR in ./src/app/components/contact-form/contact-form.component.ts
Module parse failed: Unexpected token (3:10)
You may need an appropriate loader to handle this file type.
| export class ContactForm {
|
|   private form: any;
|
|   constructor(formSelector: string) {
 @ ./src/app/main.ts 1:0-79

ERROR in ./src/app/components/slider/slider.component.ts
Module parse failed: Unexpected token (3:10)
You may need an appropriate loader to handle this file type.
| export class Slider {
|
|   private container: HTMLElement;
|   private slides: HTMLElement[];
|
 @ ./src/app/main.ts 2:0-62

Here is my webpack.common.js:

const path = require("path");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

module.exports = {
  devtool: "source-map",
  entry: {
    scripts: "./src/app/main.ts",
    styles: "./src/app/styles.scss",
  },
  resolve: {
    extensions: [".js", ".ts", ".tsx", ".scss"],
    symlinks: false,
  },
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: "/\.tsx?$/",
        use: {
          loader: "ts-loader",
          options: {
            configFile: "./tsconfig.json",
            happyPackMode: true,
            transpileOnly: true,
          },
        },
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: "style-loader",
            options: {
              insertAt: "top",
            },
          },
          {
            loader: "css-loader",
            options: { sourceMap: true },
          },
          {
            loader: "sass-loader",
            options: { sourceMap: true },
          },
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [ "file-loader" ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [ "file-loader" ],
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "src/app/index.html",
    }),
    new ForkTsCheckerWebpackPlugin({
      checkSyntaticErrors: true,
    }),
  ],
};

This is my webpack.dev.js:

const webpack = require("webpack");
const merge = require("webpack-merge");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  devServer: {
    contentBase: "./dist",
    clientLogLevel: "none",
    port: 3000,
    hot: true,
    overlay: true
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
});

Configurations found in tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist",
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "es5",
    "baseUrl": "src",
    "allowJs": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "lib": [
      "es2016",
      "dom"
    ],
    "declaration": false,
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}

Lastly, here's my package.json:

 ...
 "scripts": {
    "start": "webpack-dev-server --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
  },
  "dependencies": {
    "clean-webpack-plugin": "^0.1.17",
    "css-loader": "^0.28.7",
    "file-loader": "^1.1.5",
    "fork-ts-checker-webpack-plugin": "^0.2.9",
    "html-webpack-plugin": "^2.30.1",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "ts-loader": "^3.2.0",
    "tslint": "^5.8.0",
    "typescript": "^2.6.2",
    "uglifyjs-webpack-plugin": "^1.1.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.5",
    "webpack-merge": "^4.1.1"
  },
  "devDependencies": {
    "@types/node": "^8.0.54"
  }

Answer №1

Modify this line:

    test: "/\.jsx?$/",

by eliminating the quotation marks, turning it into a regular expression:

    test: /\.jsx?$/,

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

The proper method for organizing a nested array object - an obstacle arises when attempting to sort the array

I have a collection of data fetched from Web API 2.2 stored in an Angular array as objects. Each object represents a Client and includes properties like name, surname, and a collection of contracts assigned to that client. Here is the interface definition ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Error in Firebase Functions: Promises must be properly managed

Currently, I am in the process of creating a Firebase function using TypeScript to deliver push notifications to multiple users. However, whenever I execute the command firebase deploy --only functions, TSLint flags an error stating "Promises must be han ...

What is the process of 'initializing' an object in TypeScript?

Is it possible that retrieving a json from a mongodb database and casting it does not trigger the typescript constructor? What could be causing this issue? I have a Team class export class Team { transformations: { [transformationId: string]: Transfor ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

Issue with Angular/Chrome: The filter pipe is not able to be located

Even though this topic has been covered before, I have not found any satisfactory solutions. Here is my approach: play.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; impor ...

One potential solution for fixing the error in GetRepository of TypeORM is to check for undefined properties before attempting to access them. This error typically occurs when trying to read properties of an undefined

[Nest] 171 - 08/31/2022, 8:35:42 PM ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'getRepository') tenant-node | TypeError: Cannot read properties of undefined (reading 'getRepository') tenant-node | at Instance ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Is it necessary to list all potential strings for accessibilityRole?

When working with accessibilityRole in React Native, I am wondering if there is a way to import all the possible strings instead of typing them out manually. createAccessibilityRole(parent: Element): string { if(isLink) return 'link' return ...

Methods to acquire the 'this' type in TypeScript

class A { method : this = () => this; } My goal is for this to represent the current class when used as a return type, specifically a subclass of A. Therefore, the method should only return values of the same type as the class (not limited to just ...

Webpack now requires updating the utoprefixer plugin to replace the color-adjust property with print-color-adjust. The color-adjust shorthand is no longer supported and has been deprecated

My webpack setup includes: main.scss @import "~bootstrap/scss/bootstrap"; packages.json "engines": { "node": "14.18.1", "npm": "6.14.15" }, "devDependencies": { "@babe ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

Getting command line argument parameters in React can be achieved by utilizing the `process.argv`

Is there a way to retrieve command line argument parameters in React? I currently have a React codebase that is utilizing Webpack. When running the following commands - npm run build -- --configuration=dev or npm run build -- --configuration=qa I need t ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

What is the best way to pass a string value instead of an event in Multiselect Material UI?

Greetings, currently utilizing Material UI multi select within a React TypeScript setup. In order to modify the multi select value in the child component, I am passing an event from the parent component. Here is the code for the parent component - import ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Retrieve an array of information and convert it into an object using Angular

My previous data is displaying correctly in the chart, as shown below: @Component({ selector: 'app-inpout-bar-chart', templateUrl: './inpout-bar-chart.component.html', styleUrls: ['./inpout-bar-chart.component.scss'] }) exp ...