【问题标题】:Module is not defined error angularjs after using webpack使用 webpack 后模块未定义错误 angularjs
【发布时间】:2019-02-21 20:33:56
【问题描述】:

我的 webpack.config

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

entry: "./main.js", //relative to root of the application
output: {
    path: __dirname,
    filename: "app.bundle.js" //relative to root of the application
},
watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
},
plugins: [
    new HtmlWebpackPlugin({
        hash: true,
        title: 'My Awesome application',
        myPageHeader: 'interviewee',
        template: './_index.html',
        filename: 'index.html' //relative to root of the application
    })
]

}

main.js

    let jquery = require("./Scripts/jquery-1.9.0.js");
    let angular = require("./Scripts/angular.js");
    let ngRoute = require("./Scripts/angular-route.js");
    let bootstrap = require("./Scripts/bootstrap.js");
    let appController = require("./app.controller.js");
    let addController = require("./add.controller.js");
    let service = require("./service.js");
    let messages = require("./Scripts/angular-messages.js")

app.controller

    var MyApp = angular.module("MyApp", [
        'ngRoute',
        'ngMessages',
        'IntervieweeService'
        ]
    );
    MyApp.config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
                when('/Add', {
                    templateUrl: 'Views/add.html',
                    controller: 'AddController'
                }).

                otherwise({
                    redirectTo: '/Home'
                });
        }]
    );

添加控制器

    MyApp.controller("AddController", function ($scope, EmpApi) { ....... }

当我运行应用程序时,我得到“MyApp”未定义。我究竟做错了什么?我是 webpack 和 angularjs 的新手。你能告诉我如何解决这个问题吗?谢谢

【问题讨论】:

  • 这是缩小角码吗?

标签: angularjs webpack


【解决方案1】:

以缩小版本可以理解的方式更改您的控制器依赖项。即

MyApp.controller("AddController", function ($scope, EmpApi) { ....... }

MyApp.controller("AddController", addController);

addController.$inject = ['$scope', 'EmpApi'];

function addController($scope, EmpApi){...};

【讨论】:

  • 虽然这仍然是一个很好的建议,但如果这是主要问题,那么错误是否与缺少 $scopeEmpApi 有关,而不是与 MyApp 有关的错误?
  • 它仍然显示相同的错误。 'ReferenceError: MyApp 未定义'
  • @chiliNUT,如果格式不正确,有时会显示相同的错误。
  • @Thunfische,你能分享 HTML,如果你不使用 webpack 会怎样?另一个建议,为每件事创建单独的文件,然后尝试。
  • @Thunfische,我认为错误应该在 addController 文件中,因为您必须 import / make require - app.controller(文件名应根据功能更正)
【解决方案2】:

“MyApp”未在控制器文件中定义,因此您必须将控制器添加到“MyApp”模块中

改变

MyApp.controller("AddController", function ($scope, EmpApi) { ....... }

angular.module('MyApp').controller("AddController", function ($scope, EmpApi) { ....... }

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2019-01-15
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2016-11-03
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多