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

Converting an array of objects into a TypeScript dictionary with IDs as the key mapping

Is there a way to provide type hints for better autocompletion when accessing keys like dictionary.Germany from the following data and types? type Entry = { tld: string; name: string; population: number; }; const data: Entry[] = [ {tld: 'de&a ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

Upon initializing an Angular project from the ground up, I encountered an issue where a custom pipe I had created was not

After creating an Angular 16.1.0 application and a custom pipe, I encountered error messages during compilation. Here are the steps I took: Ran ng new exampleProject Generated a pipe using ng generate pipe power Modified the content of app.compone ...

Set values to the inner property of the object

In my configuration file, I have set up nested properties as shown below export class Config { public msalConfig: { auth: { authority: string; clientId: string; validateAuthority: boolean; redirectUri: ...

Unable to integrate BokehJS with Angular8

Here is the error log that appeared in the browser: AppComponent.html:1 ERROR TypeError: FlatBush is not a constructor at new SpatialIndex (vendor.js:90501) at AnnularWedgeView.push../node_modules/bokehjs/build/js/lib/models/glyphs/xy_glyph.js.XYG ...

Unable to locate the term "module"

I've been working on a TypeScript file that includes an exported function called sum: This script is meant to be run in Node.js. function sum(a:number):number{ return a; } module.exports.sum=sum; I'm encountering some issues and I'm not ...

Issue with subscribing to nested observables, unable to successfully unsubscribe

My app is using Firebase auth with Firestore (https://github.com/angular/angularfire2). Despite my efforts to unsubscribe from all observables fetched from Firestore before signing out, I keep encountering a "FirebaseError: Missing or insufficient permissi ...

Issue with Angular 6 and Chrome: Event listener ($event) occasionally throws the error "unable to access property 'value' of null"

It appears that the buttons are being iterated correctly using ngFor, and upon inspection they have the correct attributes. However, when clicked, the function in the controller sometimes claims the parameter is 'undefined', happening randomly ab ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

Tips for creating a TypeScript function that can accept an array of concatenated modifiers with the correct data type

Can I modify data using a chain of function modifiers with correct typing in TypeScript? Is this achievable? const addA = (data: {}) => { return { ...data, a: "test" } } const addB = (data: {}) => { return { ...data, ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Navigating Angular single page application routes within an ASP.NET Web API project

Developed an Angular single-page application with specific routes: /messages /messages/:id By using ng serve, I can navigate to these pages at URLs like localhost:4200/messages and localhost:4200/messages/:id After building the solution, I transferred t ...

Typescript: Removing signatures with a filter

I am encountering a TypeScript error stating that .filter has no signatures. I'm unsure of how to resolve this issue. interface IDevice { deviceId: string; deviceName?: string; } const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams ...