在react项目中使用JS和TS

2024-01-03

我按照此处的说明创建了一个新的反应项目https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react https://learn.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":

联系组件使用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,一切正常。我说服自己这是更容易的道路。

Thanks.


此时您的 webpack 配置已设置为加载.tsx文件使用ts-loader,但没有提到.js files!

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

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

您可以通过修改来更改它test: /\.tsx?$/, to 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>,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在react项目中使用JS和TS 的相关文章

随机推荐