如何在 typescript+webpack 项目中使用 js/jsx 文件?

ABC*_*ABC 4 typescript reactjs webpack

我正在尝试导入和使用常规.jsx文件,该typescript文件位于使用webpack. 我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

该错误消息意味着我没有指定处理jsx文件的加载程序。很公平,但是我应该使用哪个加载器?我尝试ts-loader加载jsx文件(这破坏了我的项目),但awesome-typescript-loader也不起作用。我觉得我已经做了其他推荐的事情:

  • 在我的中将“allowJs”设置为 truetsconfig.json
  • .jsx文件添加到我的 webpack 配置的解析部分。
  • 为我的 webpack 配置中的文件定义一个规则(在 module.rules 下)/\.jsx?$/

这是我的相关部分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
  },
Run Code Online (Sandbox Code Playgroud)

这是我的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
  }
}
Run Code Online (Sandbox Code Playgroud)

Ham*_*ohi 5

.tsx,.jsx您可以将其添加到一起以获取支持webpack.config.js

  {
    test: /\.(tsx|jsx|ts|js)?$/,
    use: "babel-loader",
    exclude: /node_modules/,
  }
Run Code Online (Sandbox Code Playgroud)

并将其添加到.babelrc

{
"presets": [
  "@babel/typescript", 
  "@babel/preset-env",
  ["@babel/preset-react", {"runtime": "automatic"}]
 ]
}
Run Code Online (Sandbox Code Playgroud)

最后改变package.json

"scripts": {
  "dev": "cross-env NODE_ENV=development webpack-dev-server",
  "build": "cross-env NODE_ENV=production webpack",
  "start": "serve dist"
}
Run Code Online (Sandbox Code Playgroud)

  • 我可以不用 babel 只用 tsc 来做吗? (2认同)