在React项目中使用JS和TS

时间:2019-01-31 17:11:18

标签: reactjs typescript webpack office-ui-fabric

我按照https://docs.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react

的指示创建了一个新的react项目。

它创建一个打字稿react项目。

我将现有的React JS文件复制到src目录中,并更改了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,并且一切正常。我说服自己,这是更简单的方法。

谢谢。

1 个答案:

答案 0 :(得分:0)

目前,您的Webpack配置已设置为使用.tsx加载ts-loader个文件,但没有提及.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>,