Skip to content
Advertisement

Webpack throws error when trying to use ts-loader

I’ve looked at all the Google results regarding this issue, but can’t find any reason why it won’t work in my case. I get this error:

ERROR in ./front/src/ts/index.ts
Module parse failed: 
/Users/Folder/OtherFolder/index.ts Unexpected token (4:10)
You may need an appropriate loader to handle this file type.
| alert("Hello World!");
| 
| var myName:string = "John Doe";
|

This is my webpack.config.js:

module.exports = {
    entry: './front/src/ts/index.ts',
    output: {
        filename: './front/dist/js/bundle.js'
    },
    watch: true,
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    module: {
        loaders: [
            {
                test: /.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015'],
                    plugins: ['transform-class-properties']
                }
            },
            {
                enforce: 'pre',
                test: /.js$/,
                loader: "source-map-loader"
            },
            {
                enforce: 'pre',
                test: /.tsx?$/,
                use: 'source-map-loader',
                loader: 'ts-loader'
            }
        ]
    },
    devtool: 'inline-source-map',
};

My tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./front/dist/js",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true
    }
}

For some reason, the TypeScript syntax is considered invalid and therefore the bundle won’t be created. I’ve tried running Babel after TS and vice versa, but that doesn’t solve it either. Any idea what the issue might be and how to fix it?

Advertisement

Answer

You can install the TypeScript compiler and the TypeScript loader from npm by running:

npm install --save-dev typescript ts-loader

tsconfig.json:

{
  "compilerOptions": 
  {
      "outDir": "./dist/",
      "sourceMap": true,
      "noImplicitAny": true,
      "module": "commonjs",
      "target": "es5",
      "jsx": "react",
      "allowJs": true
   }
}

webpack.config.js . A basic webpack with TypeScript config should look along these lines:

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'bundle.js',
    path: __dirname
  },
  module: {
    rules: [
      {
        test: /.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"]
  }
};
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement