【问题标题】:Angular 2 "require is not defined"Angular 2“未定义要求”
【发布时间】:2016-03-24 22:06:54
【问题描述】:

我正在开发一个以前可以运行的应用程序。我现在正在尝试添加一些路由,因此创建了一个 app.component 文件并更改了一些参数,但现在我只是得到一个空白屏幕并且控制台中出现此错误...

Error: ReferenceError: require is not defined
        at eval (http://localhost:3000/client/dev/main.js:2:17)
        at eval (http://localhost:3000/client/dev/main.js:6:3)
        at $ (http://localhost:3000/node_modules/systemjs/dist/system-polyfills.js:4:8740)
    Evaluating http://localhost:3000/client/dev/main.js
    Error loading http://localhost:3000/client/dev/main.js

我的 Main.JS 文件是:

"use strict";
var browser_1 = require('angular2/platform/browser');
var app_component_1 = require('./app.component');
browser_1.bootstrap(app_component_1.AppComponent);

这是从main.ts生成的:

import { bootstrap }    from 'angular2/platform/browser';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

这是怎么回事?

更新:

感谢 Eric 提出在 tsconfig.json 中使用系统模块的建议,但如果我这样做了,我会收到以下错误:

C:\Users\George\Source\Repos\Gen-App\server\server.js:2
System.register(['express', 'os', 'http', './config/routes.conf', './config/db.conf', './config/passport', './routes/index'], function(exports_1, context_1) {
^

ReferenceError: System is not defined
    at Object.<anonymous> (C:\Users\George\Source\Repos\Gen-App\server\server.js:2:1)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (C:\Users\George\Source\Repos\Gen-App\index.js:1:63)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

注意:我的 server.js 代码是here

【问题讨论】:

  • 检查你的tsconfig.json文件,查看“module”属性,如果是“commonjs”,改成“system”,重新编译文件。
  • 我也对此感到沮丧。除了@Eric 所说的,我必须将 tsc 升级到最新才能使用模块“系统”。
  • @EricMartinez 谢谢,这似乎奏效了,但它现在破坏了我以前工作的服务器端代码,现在抛出这个错误:ReferenceError: System is not defined,完整的细节将添加到问题中
  • 浏览器不像 Node 那样有require。您需要使用 Browserify 或 Webpack 之类的工具来编译模块。
  • @GeorgeEdwards:知道了!问题是您在同一个项目中为服务器端和客户端使用打字稿。客户端使用systemjs,服务端commonjs...

标签: javascript angularjs angular


【解决方案1】:

您说您添加了一些路由,但现在它不起作用。您的index.html 文件需要包含router.dev.js 文件:

<script src="node_modules/angular2/bundles/router.dev.js"></script>

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 1970-01-01
    • 2017-06-18
    • 2016-03-29
    • 2017-01-23
    • 2016-11-09
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多