首页 > 解决方案 > 为 mvc5 项目导出 es6 模块

问题描述

我正在尝试为 mvc5 项目(不是核心)设置 webpack。一切正常。除了在 cshtml 页面的脚本中引用模块。例如在我的布局页面中。

<script src="~/Scripts/build/bundle.js"></script>

在 main.js 中

import Person from './person';

var person = new Person("David", 20);
person.speak();

和 person.js

export default class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    speak() {
        console.log(`Hi I'm ${this.name} and ${this.age} years old and I am awesome`);
    }
}

当我运行应用程序时,这很好用,我在控制台中看到了输出。

然而,试图引用 index.cshtml 中的人给我带来了问题。

我将 main.js 更改为。

module.exports = {
    Person: require('./person'),
};

在我看来,我试图引用人

在 index.cshtml 中(正在使用布局页面)

<script>
        var person = new Person("David", 20);
        person.speak();
    </script>

我收到

未捕获的 ReferenceError:Person 未在索引处定义:64

标签: javascriptasp.net-mvcwebpackecmascript-6es6-modules

解决方案


推荐阅读