带有webpack配置的Angular 1.x.

时间:2017-07-10 08:12:30

标签: javascript angularjs webpack webpack-2

未捕获的ReferenceError:未定义myApp

我正在尝试使用Webpack设置Angular 1.x,但会收到上述错误。以下是我的配置设置和文件夹结构。让我知道Webpack我做错了什么。

文件夹结构 -

Folder Structure

index.html文件 -

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Directives - Angular</title>
    <script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
</head>
<body>
    <first-directive></first-directive>
    <second-directive></second-directive>
    <third-directive></third-directive>     
    <script type="text/javascript" src="bundle.js"></script>
</body>
</html>

app.js

var myApp = angular.module('myApp', []);

第一directive.js

myApp.directive('firstDirective', function() {
    return {
        template: '<h1>This is a first directive</h1>'
    }
})

webpack.config.js文件 -

module.exports = {
    entry: ["./app.js", "./directives/first-directive.js", "./directives/second-directive.js", "./directives/third-directive.js"],
    output: {
        filename: 'bundle.js'
    }   
};

此外,如果我使用如下所述的通配符,它​​也无效。

entry: ["./app.js", "./directives/*"]

让我知道我在使用webpack配置时遇到了什么问题。

仅供参考 - bundle.js看起来像这样 - http://codepad.org/Kd7P5Evy

1 个答案:

答案 0 :(得分:2)

根据评论,文件first-directive.js有一个变量myApp,似乎是undefined

要纠正此问题,您需要以下两种方法之一:

app.js导出模块的定义,然后将其导入first-directive.js

// app.js
export var myApp = angular.module('myApp', []);

// first-directive.js
import {myApp} from './app';

myApp.directive('firstDirective', function() {
  return {
    template: '<h1>This is a first directive</h1>'
  }
});

first-directive.js导出指令的定义,并将其导入app.js

// first-directive.js
export function firstDirective() {
  return {
    template: '<h1>This is a first directive</h1>'
  };
}

// app.js
import {firstDirective} from './first-directive';

var myApp = angular.module('myApp', [])
  .directive('firstDirective', firstDirective);