首页 文章

未定义模块,未定义导出 - 使用typescript做出反应

提问于
浏览
0

我有一个非常简单的应用程序使用ASP 4 / MVC 5和Typescript(2.3.1.0)

这是基本布局:

tsconfig.json

{

  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "jsx": "preserve",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "node_modules/@types/**/*.d.ts",
    "Scripts/**/*.ts",
    "Scripts/**/*.tsx"
  ]
}

app.tsx(使用visual studio的工具编译为app.js)

import React, { Component } from 'react';

interface FooProps {
    name: string;
}

export default class Hello extends React.Component<FooProps, undefined> {
    render() {
        return <h1>Hello from {this.props.name} !</h1>
    }
}

_Layout.cshtml

<body>
    @RenderBody()

    <script type="text/javascript" src="~/Scripts/jquery-2.2.4.js"></script>
    <script type="text/javascript" src="~/node_modules/react/react.js"></script>
    <script type="text/javascript" src="~/node_modules/react-dom/dist/react-dom.js"></script>
    <script type="text/javascript" src="~/Scripts/app.js"></script>
</body>

当我运行时,它会出现在控制台中:
enter image description here

我试图这样做而不使用像browserify / webpack这样的东西 . 我的问题是,它有可能......如果是的话,怎么样?

Edit

在tsx - > jsx转换后,app.jsx看起来像这样:

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var Hello = (function (_super) {
    __extends(Hello, _super);
    function Hello() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Hello.prototype.render = function () {
        return <h1>Hello from {this.props.name} !</h1>;
    };
    return Hello;
}(react_1.default.Component));
//# sourceMappingURL=app.jsx.map

注意,这里抛出错误:

Object.defineProperty(exports, "__esModule", { value: true });

未捕获的ReferenceError:未定义导出

1 回答

  • 1

    “我试图在不使用像browserify / webpack这样的东西的情况下做到这一点” - 简短的回答是否定的 . 任何浏览器目前不支持ES2015导入/导出语法 . 因此,如果没有某种转换步骤,我不确定您希望它如何在浏览器中运行 . 最流行的方法是使用Webpack / Babel,但你可以使用Babel ....

    如果你真的想避免任何反编译,你将不得不避免将来的语言功能 . 因此 ReactReactDOM 必须位于全局命名空间中,并且所有组件必须位于同一文件中,或者加载到全局命名空间中 . 我觉得这将是一场艰苦的战斗,但它肯定是可行的 .

相关问题