简体   繁体   English

在 React 项目中使用 JS 和 TS

[英]Using JS and TS in a react project

I created a new react project by following directions here 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

It creates a typescript react project.它创建了一个 typescript 反应项目。

I copied my existing react JS files in the src directory and changed ts.config to say我将现有的 React JS 文件复制到 src 目录中,并将 ts.config 更改为

"allowJs": true,

Running npm start gives errors运行 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 uses react-router-dom ContactComponent 使用 react-router-dom

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

My ts.config is as follows我的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
}

my webpack.config.js is我的 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"]
        })
    ]
};

There has to be way to get JS and TSX to play nicely and compile and I tried couple of options I found like using awesome-typescript-loader which I installed and used but I get the same error.必须有办法让 JS 和 TSX 很好地运行和编译,我尝试了几个我发现的选项,比如使用我安装和使用的 awesome-typescript-loader,但我得到了同样的错误。

Has anyone tried mixing JS components with React Components and get those two to work together?有没有人尝试过将 JS 组件与 React 组件混合并让这两者协同工作?

I converted the JS files to tsx and everything is working.我将 JS 文件转换为 tsx,一切正常。 I convinced myself that this was the easier path.我说服自己,这是更容易的道路。

Thanks.谢谢。

At the moment your webpack config is set to load up .tsx files using ts-loader , but there's no mention of .js files!目前你的 webpack 配置设置为使用ts-loader .tsx文件,但没有提到.js文件!

This lines up with the error message you're getting, which comes from webpack, and not TypeScript:这与您收到的错误消息一致,该消息来自 webpack,而不是 TypeScript:

You may need an appropriate loader to handle this file type.您可能需要一个合适的加载器来处理这种文件类型。

You can change that by modifying test: /\\.tsx?$/, to test: /\\.(tsx|ts|js)$/, .你可以通过修改test: /\\.tsx?$/,来改变它test: /\\.(tsx|ts|js)$/,

To test this I created Foo.js:为了测试这个,我创建了 Foo.js:

export var foo = "foo Welcome foo";

And Foo.d.ts (don't forget, if you want to use JS with TS, then it needs to have typings):还有 Foo.d.ts(别忘了,如果你想在 TS 中使用 JS,那么它需要有类型):

export var foo: string;

Then in index.tsx I imported foo:然后在 index.tsx 中我导入了 foo:

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

And used it:并使用它:

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

I think you are defining Jsx syntax in a file which has extension.js, thus could be the problem.我认为您在具有 extension.js 的文件中定义 Jsx 语法,因此可能是问题所在。 Trying renaming file extension to.jsx and add.jsx in webconfig尝试在 webconfig 中将文件扩展名重命名为 .jsx 和 add.jsx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM