尝试使用ts-loader时,Webpack会引发错误

时间:2017-05-10 15:48:13

标签: javascript webpack

我已经查看了有关此问题的所有Google搜索结果,但无法找到任何原因导致我无法解决此问题。我收到这个错误:

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";
|

这是我的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',
};

我的tsconfig.json:

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

由于某种原因,TypeScript语法被视为无效,因此无法创建捆绑包。我曾尝试在TS之后运行Babel,反之亦然,但这也无法解决。知道问题可能是什么以及如何解决它?

1 个答案:

答案 0 :(得分:1)

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"]
  }
};