reactjstypescriptwebpackoffice-ui-fabric

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

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.


Solution

  • 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>,