wix-incubator / react-templates

Light weight templates for react
https://wix.github.io/react-templates
MIT License
2.82k stars 207 forks source link

react-templates, TypeScript, Webpack #238

Open davidrapin opened 6 years ago

davidrapin commented 6 years ago

Hi,

This is a question and/or an issue, since at this stage I'm not sure if I'm doing something wrong. I can't seem to make react-templates, TypeScript and Webpack work together.

webpack.config.js:

module.exports = {
  // [...]
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.rt', '.es6', '.json', '.scss', '.css'],
    plugins: [ new TsconfigPathsPlugin() ]
  },
  // [...]
   module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        include: SRC_FOLDER,
        exclude: ['/node_modules/']
      },
      {
        test: /\.rt$/,
        loader: 'react-templates-loader?modules=commonjs',
        include: SRC_FOLDER,
      }
    ]
  }
}

TemplateExample.ts:

import * as React from 'react';
import { RouteComponentProps } from "react-router";
import template = require('./TemplateExample.rt');

export interface TemplateExample extends RouteComponentProps<any> {}
export class TemplateExample extends React.Component<TemplateExample, any> {

    getWorld(): string {
        return 'World!';
    }

    render() {
        return template.apply(this);
    }
}

 TemplateExample.rt:

<div>
    <strong>Hello {this.getWorld()} :)</strong>
</div>

Of course, both TemplateExample.ts and  TemplateExample.rt are in the same folder.

Error message

ERROR in /Users/david/Code/platypus/client/src/components/_Integration/TemplateExample.ts
./src/components/_Integration/TemplateExample.ts
[tsl] ERROR in /Users/david/Code/platypus/client/src/components/_Integration/TemplateExample.ts(11,27)
      TS2307: Cannot find module '/Users/david/Code/platypus/client/src/components/_Integration/TemplateExample.rt'.

I tried to change the modules option of the Webpack loader to typescript , in which case I get this error (which clarifies that the issue is not with the location of the template file):

ERROR in ./src/components/_Integration/TemplateExample.rt
Module parse failed: Unexpected token (1:13)
You may need an appropriate loader to handle this file type.
| import React = require('react');
| import _ = require('lodash');
| export = function() { return React.createElement('div',{},React.createElement('strong',{},"Hello ",(this.getWorld())," :)")) };
 @ ./src/components/_Integration/TemplateExample.ts 20:15-46
 @ ./src/components/Router.tsx
 @ ./src/components/App.tsx
 @ ./src/components/Root.tsx
 @ ./src/app.tsx
 @ multi ./src/app.tsx

Any feedback would be welcome!

idok commented 6 years ago

Here is a working sample https://github.com/wix/react-templates-ts