简体   繁体   中英

VS2017: Using JSX components from react theme in ASP.NET Core React Redux web application template

I've created a project using Visual Studio 2017 preview using the ASP.NET Core "React.js and Redux" project type.

I'm now trying to include components from a theme and we're running into some issues I haven't been able to resolve with extensive googling. I suspect I am misunderstanding how to use webpack. I've boiled it down to an extremely simple test case below.

Note: I have "allowJs": true in my tsconfig.json because it complains about not having the --allowJs flag when I try to import a jsx file otherwise.

This issue looks suspiciously similar to this issue: import jsx file in tsx compilation error but I believe this one is distinct and googling hasn't gotten me anywhere.

What I've tried:

  • setting "jsx" to "react", "react-native", and "preserve"
  • creating separate rule under sharedConfig in webpack.config.js (probably incorrectly?)
  • adding a rule for jsx and installing babel-core
  • Changing settings more or less at random in tsconfig.json and webpack.config.js
  • Too much googling

the error:

NodeInvocationException: Prerendering failed because of error: Error: Module parse failed: D:\MyProject\ClientApp\components\Card.jsx Unexpected token (5:12)
You may need an appropriate loader to handle this file type.
| render(){
| return (
| <div> Test </div>
| );
| }
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:21692:7)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8547:64)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8445:75)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8498:66)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at D:\MyProject\ClientApp\dist\main-server.js:66:18
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:69:10)
Current directory is: D:\MyProject

Home.tsx

import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { ApplicationState } from '../store';
import Card from './Card';

type HomeProps = RouteComponentProps<{}>;

export default class Home extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        return <div>
            <Card></Card>
        </div>
    }
}

Card.jsx

import React, { Component } from 'react';
class Card extends Component{
    render(){
        return (
            <div> Test </div>
        );
    }
}
export default Card;

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');

module.exports = (env) => {
    const isDevBuild = !(env && env.prod);

    // Configuration in common to both client-side and server-side bundles
    const sharedConfig = () => ({
        stats: { modules: false },
        resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    });

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig(), {
        entry: { 'main-client': './ClientApp/boot-client.tsx' },
        module: {
            rules: [
                { test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
            ]
        },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new ExtractTextPlugin('site.css'),
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig(), {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot-server.tsx' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ],
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "sourceMap": true,
    "skipDefaultLibCheck": true,
    "strict": true,
    "lib": ["es6", "dom"],
    "types": [ "webpack-env" ],
    "allowJs": true
  },
  "exclude": [
      "bin",
      "node_modules"
  ]
}

To fix this we had to add some stuff to package.json and webpack to support babel loader. This hasn't been working perfectly, but it's gotten us a step closer to having things work properly. This is due to some unresolved typing issues.

Package.json

"babel-core":"6.26.0",
"babel-loader": "7.1.4",
"babel-preset-es2015": "6.24.1",
"babel-preset-react": "6.24.1",

Webpack.config.js:

    module: {
        rules: [
            { test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
            { test: /\.(png|jpg|jpeg|gif)$/, use: 'url-loader?limit=25000' },
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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