簡體   English   中英

當 Webpack ts-loader 顯示“模塊解析失敗:意外令牌”時,tsconfig.json jsx 被保留

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

我想用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>;

如果jsx是react,就沒有這個錯誤,這個問題怎么處理?

這是我的一些文件:

配置文件

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

索引.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>
  }
}

包.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

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 })
  ]
}

我能夠通過添加babel-loader來解決類似的問題。 嘗試這樣的事情:

  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