typescript - 当 Webpack ts-loader 显示“模块解析失败:意外令牌”时,tsconfig.json jsx 被保留
问题描述
我想用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,就没有这个错误,请问这个问题怎么处理?
以下是我的一些文件:
tsconfig.json
{
"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'
},
],
},
推荐阅读
- android - 如何在图像视图中显示的图库中选择图像上添加扫描动画。指纹扫描等动画
- yii - Yii::app()->会话不工作
- xmpp - XMMP 服务器设置
- kubernetes - Pod 优先级和抢占
- wireshark-dissector - Wireshark:自定义解析器信息字段并不总是显示
- android - 如何以编程方式从 sdcard/storage .apk 文件中获取 appicon?
- sql-server - 使用嵌套聚合查询的最大 SUM
- java - 在我的 JSP 页面中,对于 ajax 多部分表单数据提交,upload.parseRequest(request) 在未上传图像时返回空列表
- opencv - 如何获取 VideoCapture::read 获取的帧的 PTS 或帧号?
- elasticsearch - Flink with Elasticsearch6.0.0 Sink NoSuchMethodError BulkProcessor.builder