【问题标题】:Using JS and TS in a react project在 React 项目中使用 JS 和 TS
【发布时间】:2021-10-11 02:24:27
【问题描述】:

我按照这里https://docs.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react的指示创建了一个新的反应项目

它创建了一个打字稿反应项目。

我在 src 目录中复制了我现有的 react JS 文件并将 ts.config 更改为说

"allowJs": true,

运行 npm start 会报错

    ERROR in ./components/folder/ContactComponent.js 176:13
Module parse failed: Unexpected token (176:13)
You may need an appropriate loader to handle this file type.
|       const { cookies } = this.props;
|       cookies.set('cookieUserToken', "", { path: '/'})
>       return <Redirect to="/login" />;
|     }

|
 @ ./components/App.tsx 64:25-65
 @ ./index.tsx
 @ multi ../node_modules/webpack-dev-server/client?https://localhost:3000 ../node_modules/webpack/hot/dev-server.js react-hot-loader/patch ./index.tsx

ERROR in ./components/Login/LoginComponent.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| function LoginComponent() {
|   return (
>     <div id="content-main" className="login">
|       <div className="padding">
|         <div className="card card-container">
 @ ./components/App.tsx 63:23-56
 @ ./index.tsx
 @ multi ../node_modules/webpack-dev-server/client?https://localhost:3000 ../node_modules/webpack/hot/dev-server.js react-hot-loader/patch ./index.tsx
Child html-webpack-plugin for "function-file\function-file.html":

ContactComponent 使用 react-router-dom

render() {
    if (this.state.cookieUrl === "" || this.state.cookieToken === "") {
      const { cookies } = this.props;
      cookies.set('cookieToken', "", { path: '/'})
      return <Redirect to="/login" />;
    }

我的ts.config如下

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "outDir": "dist",
    "allowUnusedLabels": false,
    "noImplicitReturns": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "allowJs": true,
    "lib": [
      "es7",
      "dom"
    ],
    "pretty": true,
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

我的 webpack.config.js 是

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");

module.exports = {
    devtool: 'source-map',
    entry: {
        app: './src/index.ts',
        'function-file': './function-file/function-file.ts'
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.html', '.js']
    },
    module: {
        rules: [
            {
                test: /\.(tsx|ts|js)$/,
                exclude: /node_modules/,
                use: 'ts-loader'
            },
            {
                test: /\.html$/,
                exclude: /node_modules/,
                use: 'html-loader'
            },
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html',
            chunks: ['app']
        }),
        new HtmlWebpackPlugin({
            template: './function-file/function-file.html',
            filename: 'function-file/function-file.html',
            chunks: ['function-file']
        }),
        new webpack.ProvidePlugin({
            Promise: ["es6-promise", "Promise"]
        })
    ]
};

必须有办法让 JS 和 TSX 运行良好并进行编译,我尝试了几个我发现的选项,比如使用我安装和使用的 awesome-typescript-loader,但我得到了同样的错误。

有没有人尝试过将 JS 组件与 React 组件混合并让这两者一起工作?

我将 JS 文件转换为 tsx,一切正常。我说服自己这是更容易的方法。

谢谢。

【问题讨论】:

  • /components/folder/ContactComponent.js 中的第 12 行是什么,因为那是发生错误的地方。在发布带有行参考的错误消息时,请包括相关行。文件是普通的javascript可能不是问题。
  • 更新了代码和错误信息

标签: reactjs typescript webpack office-ui-fabric


【解决方案1】:

目前,您的 webpack 配置设置为使用 ts-loader 加载 .tsx 文件,但没有提及 .js 文件!

这与您收到的错误消息一致,它来自 webpack,而不是 TypeScript:

您可能需要适当的加载程序来处理此文件类型。

您可以通过将 test: /\.tsx?$/, 修改为 test: /\.(tsx|ts|js)$/, 来更改它。

为了测试这一点,我创建了 Foo.js:

export var foo = "foo Welcome foo";

还有Foo.d.ts(别忘了,如果你想用JS和TS一起使用,那么它需要有类型):

export var foo: string;

然后在 index.tsx 中我导入了 foo:

import { foo } from './components/Foo';

并使用它:

<AppContainer>
    <>
        <h1>{foo}</h1>
        <Component title={title} isOfficeInitialized={isOfficeInitialized} />
    </>
</AppContainer>,

【讨论】:

  • 嗨,安迪,我尝试了你的建议,但我仍然在 static propTypes = { 行遇到同样的错误,我认为还有其他事情发生。所以为了确认,我评论了 propTypes 行,然后它在 return ;然后我评论了那行,它抛出了一个错误 header =
  • 好吧,从一个新项目开始,并按照我给你的说明给你一个工作项目。将相同的东西应用于您现有的项目是行不通的。因此,您需要从没有任何更改的工作项目开始,然后一一应用它们。这会告诉您什么不起作用,以便您可以针对它找到解决方案。
  • 再看一遍,我认为问题可能是您尝试使用 JSX,而不是 JS。
  • 我尝试了很长时间来调整和切换设置,但它似乎不想接受 JSX 语法。 TS GitHub 上的各种问题都表明这是可能的,所以我想我只是还没有找到正确的组合……抱歉,我没有更好的信息。
  • @iJK 因此,如果您要将 TS 添加到具有许多 .js 文件的新项目中。您需要将它们全部转换为 .ts 或 .tsx?
【解决方案2】:

我认为您在扩展名为 .js 的文件中定义 Jsx 语法,因此可能是问题所在。尝试将文件扩展名重命名为 .jsx 并在 webconfig 中添加 .jsx

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2023-02-25
  • 2020-01-23
  • 2020-11-02
  • 1970-01-01
  • 2020-06-05
  • 2021-10-24
  • 2020-02-24
  • 2018-12-11
  • 2021-09-15
相关资源
最近更新 更多