Реакция связывания / машинопись с помощью babel / webpack - PullRequest
0 голосов
/ 22 марта 2020

У меня есть ASP. Net MVC проект с использованием машинописи и реакции, и я пытаюсь связать свои файлы, используя webpack и babel.

В машинописи мне пришлось экспортировать свой компоненты, чтобы иметь возможность использовать их в нескольких файлах. Все это нормально связано, но это означает, что в конечном файле .jsx есть декларации экспорта.

Когда я пытаюсь связать выходной файл .jsx с веб-пакетом, я получаю следующую ошибку Error: Plugin/Preset files are not allowed to export objects, only functions.

Я попытался установить несколько плагинов Babel, которые предположительно решают эту проблему без какой-либо удачи.

Я чувствую, что что-то упустил. Как я могу удалить эти экспортные декларации или сделать так, чтобы babel играла хорошо? Спасибо

VehiclePanel.tsx

import { Component } from 'react';
import { IVehicle } from "../../Interfaces/Interfaces";

export class VehiclePanel extends Component<IVehicle> {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="box">
                <div className="box-header with-border">
                    <h3 className="box-title">{this.props.VehicleName}</h3>
                    <div className="box-tools pull-right" style={{ marginTop: "-20px" }}>
                        <h3><a href="NewService"><span className="label label-primary">New Service</span></a>
                        <a href={"EditVehicle/" + this.props.VehicleGuid}><span className="label label-primary">Edit</span></a></h3>
                    </div>
                </div>
                <div className="box-body">
                    VIN:                           <div className="box-tools pull-right"> Service Due Date: </div><br/>
                    {this.props.Vin}               <div className="box-tools pull-right"> {this.props.ServiceDueDate}  </div><br/><br/>
                    Fire Extinguisher:             <div className="box-tools pull-right"> Fire Extinguisher Inspection Due:</div><br/>
                    {this.props.FireExtinguisherSerial}  <div className="box-tools pull-right"> {this.props.FireExtinguisherInspectionDueDate}  </div><br/><br/>
                    Person Responsible:            <div className="box-tools pull-right"> Last Inspected:   </div><br/>
                    {this.props.PersonResponsible} <div className="box-tools pull-right"> {this.props.LastInspected}  </div>
                </div>
                <div className="box-footer"></div>
            </div>
        );
    }
}

VehiclePage.tsx (Расходует VehiclePanel)

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { IVehicle } from "../../Interfaces/Interfaces";
import { VehiclePanel } from '../General/VehiclePanel';

interface IVehiclePageProps {
    data: IVehicle[];
}

interface IVehiclePageState {
    data: IVehicle[];
}

class VehiclesPage extends React.Component<IVehiclePageProps, IVehiclePageState> {

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.setState({ data: this.props.data });
    }

    render() {
        var vehiclePanels = this.state.data.map(function (vehicle) {
            console.log(vehicle);
            return (<VehiclePanel
                Vin={vehicle.Vin}
                ArchivedDate={vehicle.ArchivedDate}
                ServiceDueDate={vehicle.ServiceDueDate}
                FireExtinguisherSerial={vehicle.FireExtinguisherSerial}
                FireExtinguisherInspectionDueDate={vehicle.FireExtinguisherInspectionDueDate}
                PersonResponsible={vehicle.PersonResponsible}
                LastInspected={vehicle.LastInspected}
                VehicleGuid={vehicle.VehicleGuid}
                Description={vehicle.Description}
                KmsHrs={vehicle.KmsHrs}
                VehicleName={vehicle.VehicleName} />);
        });

        return (
            <div className="commentBox">
                <section className="content-header">
                    <h1>
                    Vehicles
                    <small>Vehicles description</small>
                    <div className="box-tools pull-right">
                        <a href="/EditVehicle/00000000-0000-0000-0000-000000000000"><span className="label label-primary">Add</span></a>
                    </div>
                    </h1>
                </section>
                <section className="content container-fluid">
                    {vehiclePanels}
                </section>
            </div>
        );
    }
}
ReactDOM.render(<VehiclesPage data={(JSON.parse((document.getElementById('JSON') as HTMLInputElement).value) as IVehicle[])} />, document.getElementById('content'));

VehiclePanel.jsx (вывод, начало файла)

import { Component } from 'react';
export class VehiclePanel extends Component {
    constructor(props) {
        super(props);
    }

webpack.config. js

const path = require('path');
const webpack = require('webpack');

const jsxConfig = {
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.ProvidePlugin({
            'jquery': 'jquery'
        }),
        new webpack.ProvidePlugin({
            'React': 'react'
        }),
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.css'],
    },
    node: {
        fs: "empty",
        module: "empty"
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['react']
                    }
                },
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },
    //mode: 'development'
    mode: 'production'
}


const vehicles = Object.assign({}, jsxConfig, {
    entry: './built/Components/Vehicles/VehiclePage.jsx',
    output: { filename: 'vehicles.jsx', path: path.resolve(__dirname, 'Content/dist/js'), },
});


const editVehicle = Object.assign({}, jsxConfig, {
    entry: './built/Components/Vehicles/EditVehiclePage.jsx',
    output: { filename: 'editVehicle.jsx', path: path.resolve(__dirname, 'Content/dist/js'), },
});


module.exports = [ vehicles, editVehicle ];

tsconfig. json

{
  "compileOnSave": true,
  "compilerOptions": {
    "outDir": "./built",
    "allowJs": true,
    "target": "ESNext",
    "jsx": "preserve",
    "lib": [ "es2015", "es2016", "dom" ],
    "module": "ESNext",
    "moduleResolution": "Node",
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "include": [
    "./Scripts/Components/**/*"
  ],
  "exclude": [
    "./Scripts/Interfaces/*"
  ]
}
...