简体   繁体   English

当 Webpack ts-loader 显示“模块解析失败:意外令牌”时,tsconfig.json jsx 被保留

[英]tsconfig.json jsx is preserve when Webpack ts-loader shows "Module parse failed: Unexpected token"

I want to convert .tsx to .jsx using Webpack, I searched some information and found that just set the jsx in tsconfig.json to preserve, But the webpack ts-loader parsing failed, It shows the error code:我想用webpack将.tsx转为.jsx,查了一些资料,发现只是在tsconfig.json中设置了jsx保存,但是webpack ts-loader解析失败,显示错误代码:

ERROR in ./index.tsx 4:15
Module parse failed: Unexpected token (4:15)
You may need an appropriate loader to handle this file type.
| export default class Home extends React.Component {
|     render() {
>         return <div>
|       <p>hello world</p>
|     </div>;

If jsx is react, there is no such error, How can I deal with this problem?如果jsx是react,就没有这个错误,这个问题怎么处理?

Here are some of my files:这是我的一些文件:

tsconfig.json配置文件

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "preserve"
  },
  "compileOnSave": false
}

index.tsx索引.tsx

import * as React from 'react'

type Props = {}

export default class Home extends React.Component<Props>{
  render(): React.ReactNode {
    return <div>
      <p>hello world</p>
    </div>
  }
}

package.json包.json

{
  "name": "test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "fork-ts-checker-webpack-plugin": "^0.5.2",
    "happypack": "^5.0.1",
    "ts-loader": "^5.3.3",
    "typescript": "^3.3.3",
    "webpack": "^4.29.3",
    "webpack-cli": "^3.2.3"
  },
  "dependencies": {
    "react": "^16.8.1"
  }
}

webpack.config.js webpack.config.js

const fs = require('fs')
const path = require('path')
const HappyPack = require('happypack')
const os = require('os')
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length })
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')

module.exports = {
  entry: './index.tsx',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js'
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: 'happypack/loader?id=ts'
      }
    ]
  },
  plugins: [
    new HappyPack({
      id: 'ts',
      loaders: [
        {
          loader: 'ts-loader',
          query: { happyPackMode: true }
        }
      ],
      threadPool: happyThreadPool,
      verbose: true
    }),
    new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true })
  ]
}

I was able to fix a similar issue by adding babel-loader .我能够通过添加babel-loader来解决类似的问题。 Try something like this:尝试这样的事情:

  rules: [
    {
      test: /\.(tsx|ts)$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
        },
        {
          loader: 'happypack/loader?id=ts'
        },
      ],
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM