【问题标题】:Angular 1.x with webpack configuration带有 webpack 配置的 Angular 1.x
【发布时间】:2017-12-13 21:12:47
【问题描述】:

Uncaught ReferenceError: myApp is not defined

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

文件夹结构 -

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', []);

first-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

【问题讨论】:

  • 你能给我们看看你的app.js文件吗?
  • @31piy 更新了问题
  • 这就是文件的全部内容吗?
  • @31piy 是的,暂时只有一行

标签: javascript angularjs webpack webpack-2


【解决方案1】:

根据cmets,文件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);

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 2016-12-17
    • 2017-06-30
    • 2017-06-03
    • 2020-02-19
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多