【发布时间】:2021-07-17 16:47:19
【问题描述】:
我正在尝试导入并使用一个常规的.jsx 文件,该文件位于我用webpack 构建的typescript 项目中。我收到此错误:
ERROR in ./src/components/App/Test.jsx 72:4
Module parse failed: Unexpected token (72:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| return (
> <span>
| Search:{' '}
| <input
错误消息暗示我没有指定加载程序来处理jsx 文件。很公平,但我应该使用哪个装载机?我尝试了ts-loader 加载jsx 文件(这破坏了我的项目)和awesome-typescript-loader 也没有工作。我觉得我已经完成了其他推荐的事情:
- 在我的
tsconfig.json中将“allowJs”设置为 true - 将
.jsx文件添加到我的 webpack 配置的解析部分。 - 在我的 webpack 配置中为
/\.jsx?$/文件定义一个规则(在 module.rules 下)。
这是我webpack.config.js的相关部分:
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
},
{
test: /\.m?jsx?$/,
resolve: {
fullySpecified: false, // disable the behaviour
},
}
],
},
resolve: {
extensions: [".tsx", ".ts", ".js",".jsx"],
symlinks: true
},
这是我的tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict" : true,
"esModuleInterop": true,
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
/* Manual */
"jsx" : "react",
"allowJs": true
}
}
【问题讨论】:
-
当它包含 jsx 时,你是否有理由称它为 js 文件?
-
@ChrisFarmer 我相应地更新了问题。当我将其更改为
jsx文件时,也会发生同样的错误(因为它本来应该是这样的)。 -
@SeanW 做了所有这些但得到了这个错误:ibb.co/Jz2hjpd。除此之外,我收到另一个错误说
Cannot find module X. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?)。另外,我的 typescript 项目运行得很好,没有在tsconfig.json中指定include,也许是因为我小心地在我的 webpack 配置中定义了entry。 -
@SeanW 是的,我的意思是,我已经有一个运行良好的 typescript+webpack 项目。我根本无法在其中添加 1 个 .jsx 文件
-
@SeanW 我使用了他们的 tsconfig 但得到了同样的错误;即我没有为
jsx文件指定加载程序。解决我的问题的方法是对 js/jsx 文件使用babel-loader,对 ts/tsx 文件使用ts-loader。
标签: reactjs typescript webpack