首页 文章

Angular 2.0.0-beta.15&webpack:“找不到名字'require' . ”

提问于
浏览
0

我最近将基于webpack的Angular 2应用程序从2.0.0-beta.2升级到2.0.0-beta.15 . 我在编译时遇到了很多错误,其中很多都是通过添加行来解决的:

/// <reference path="../node_modules/angular2/typings/browser.d.ts" />

到我的bootstrap文件 . 但是,我仍然收到很多与 require 有关的错误:

error TS2304: Cannot find name 'require'.

TypeScript加载器使用的是1.8.10版本的编译器,我的tsconfig.json如下所示:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noEmitHelpers": false,
    "sourceMap": true,
    "moduleResolution": "node"
  },
  "filesGlob": [
    "./app/**/*.ts",
    "!./node_modules/**/*.ts"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

我还需要做些什么来实现这个目标?对我来说这是一个真正的阻碍者!

2 回答

  • 2

    您应该使用typings之类的工具为模块添加类型定义 .

    全局安装:

    npm i -g typings
    

    为它创建一个配置:

    typings init
    

    有一个使用require的类型定义 .

    typings install require --ambient --save
    

    请注意,typings将为main和浏览器添加类型定义,对tsconfig.json文件进行更改以仅包含浏览器版本 .

    "filesGlob": [
        "./app/**/*.ts",
        "!./node_modules/**/*.ts",
        "!./typings/main",
        "!./typings/main.d.ts"
      ],
    
  • 3

    创建定义文件,如 declarations.d.ts ,内容为:

    //fix error TS2304: Cannot find name 'require':
    declare function require(string:string):any;
    

    并添加对 main.ts / boot.ts 的引用:

    /// <reference path="./typings/declarations.d.ts" />
    

相关问题