Skip to content
Advertisement

Webpack fails to parse typescript files. Module parse failed: Unexpected token

I was setting up Typescript and Webpack on an old project of mine and suddenly encountered this 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

Then I have created a new project from scratch that goes as follow:

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();

… and the error appears 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, what it can be?

ps: I have tried also different loaders as ts-loader and awesome-typescript-loader.

Thanks! Any help is appreciated :*

Advertisement

Answer

The root cause is that your Typescript rule isn’t matching (“currently no loaders are configured to process this file”), so Webpack is reading your TS files as Javascript and getting thrown by the TypeScript-specific : on line 2 character 12. From your webpack.config.js:

test: '/.ts$',

This should be a regular expression. Note the lack of single quotes:

test: /.ts$/,

See Webpack docs Rule.test and Condition for more.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement