setagana
setagana

Reputation: 169

Unexpected token with Webpack and React

I'm new to TypeScript and relatively new to React and just trying to follow the React & Webpack tutorial. With some searching I've managed to resolve most of the issues with it being slightly out of date, except one. When I try and run Webpack to transpile the Typescript, I get:

ERROR in ./src/index.tsx
Module parse failed: /home/X/Projects/react-typescript-tutorial/src/index.tsx Unexpected token (7:4)
You may need an appropriate loader to handle this file type.
| 
| ReactDOM.render(
|     <Hello compiler="TypeScript" framework="React" />,
|     document.getElementById("example")
| );

I tried the solution mentioned in this previous question but it had no effect in my case. I'm not sure if this is an issue with awesome-typescript-loader at this point or with Webpack.

My webpack.config.js file:

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    devtool: "source-map",

    resolve: {
        extensions: ["*", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" }
        ],

        rules: [
            { test: /\.js$/, enforce: "pre", loader: "source-map-loader" }
        ]
    },

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },
};

My tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ]
}

And (as requested in comments) my index.tsx file:

import * as React from "react";
import * as ReactDOM from "react-dom";

import { Hello } from "./components/Hello";

ReactDOM.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementById("example")
);

Would appreciate any help available!

Upvotes: 3

Views: 877

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32972

You defined both module.rules and module.loaders. When webpack sees module.rules it ignores module.loaders completely, which only exist for compatibility reasons. So your awesome-typescript-loader is not being used at all. To fix it simply put all rules under modules.rules:

module: {
   rules: [
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      { test: /\.js$/, enforce: "pre", loader: "source-map-loader" }
   ]
},

Upvotes: 9

Related Questions