Using JS and TS in a react project
Asked Answered
A

2

7

I created a new react project by following directions here https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react

It creates a typescript react project.

I copied my existing react JS files in the src directory and changed ts.config to say

"allowJs": true,

Running npm start gives errors

    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

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

{
  "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

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.

Has anyone tried mixing JS components with React Components and get those two to work together?

I converted the JS files to tsx and everything is working. I convinced myself that this was the easier path.

Thanks.

Artwork answered 31/1, 2019 at 17:11 Comment(2)
What is the line 12 in /components/folder/ContactComponent.js because that is where the error occures. Please include the relevant lines when posting error messages with line references. It is likely not a problem with the file being normal javascript.Ochlocracy
updated the code and error messageArtwork
H
2

At the moment your webpack config is set to load up .tsx files using ts-loader, but there's no mention of .js files!

This lines up with the error message you're getting, which comes from webpack, and not 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)$/,.

To test this I created 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):

export var foo: string;

Then in index.tsx I imported foo:

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

And used it:

<AppContainer>
    <>
        <h1>{foo}</h1>
        <Component title={title} isOfficeInitialized={isOfficeInitialized} />
    </>
</AppContainer>,
Hargis answered 31/1, 2019 at 17:33 Comment(6)
Hi Andy, I tried what you suggested and I still get the same error at the line static propTypes = { and I think something else is going on. So to confirm, I commented propTypes line and then it threw an error at return <Redirect to="/login" />; then I commented that line and it threw an error header = <ContactItemHeader headerText={contact.Group_Value}></ContactItemHeader>Artwork
Well, starting with a fresh project and following the instructions I gave gives you a working project. Applying the same thing to your existing project doesn't work. So you need to start with the working project that has none of your changes in, then apply them one by one. that'll tell you what isn't working so you can target it to find a solution.Hargis
Having another look, I think the problem might be you're trying to use JSX, rather than JS.Hargis
I tried for quite a while to tweak and toggle the settings, and it just doesn't seem to want to accept the JSX syntax. Various issues on the TS GitHub imply it's possible, so I think I just haven't found the right combination yet ... sorry I haven't got any better info.Hargis
Thanks Andy. I found out it was quite easy to convert my app to TypeScript and doing that obviously fixed all the issues.Artwork
@Artwork so if you are adding TS to a new project which has many .js files. You need to convert all of them to either .ts or .tsx?Fuss
B
0

I think you are defining Jsx syntax in a file which has extension .js, thus could be the problem. Trying renaming file extension to .jsx and add .jsx in webconfig

Benue answered 10/10, 2021 at 18:24 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Oralla

© 2022 - 2024 — McMap. All rights reserved.