AngularJs + Typescript:错误TS2307:找不到模块'angular'

Ste*_*rov 8 angularjs typescript typescript-types

我正在尝试组合Angular1.5 + Typescript.已安装所需类型:

npm install @types/angularjs

但仍然看到错误:

错误TS2307:找不到模块'angular'

已尝试过不同的选择:

import 'angular';
import 'angularjs'; //that is name inside @types
import angular from 'angularjs';
import * as angular from 'angular';
Run Code Online (Sandbox Code Playgroud)

我正在使用:

"ts-loader": "1.0.0",
"typescript": "2.0.7",
"webpack": "1.13.3",
"webpack-dev-server": "1.16.2"
Run Code Online (Sandbox Code Playgroud)

tsconfig非常标准:

{
  "compilerOptions": {
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": false,
    "lib": ["es6", "dom"],
    "typeRoots": ["./node_modules/@types"]
  },
  "exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)

已经简化了webpack配置:var webpack = new require('webpack');

module.exports = {
  context: __dirname + '/src',
  entry: './index.ts',
  output: {
    path: './dist',
    filename: 'app.bundle.js'
  },
  module: {loaders: [{test: /\.tsx?$/, loader: 'ts-loader'},]},
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
  },

  plugins: [new webpack.NoErrorsPlugin()],

  devtool: 'source-map',

  devServer: {
    contentBase: './dist',
    historyApiFallback: true,
    inline: true
  }
};
Run Code Online (Sandbox Code Playgroud)

我还简化了index.ts本身,只关注类型导入:

import * as angular from 'angular';
angular.module('testmodule', []);
Run Code Online (Sandbox Code Playgroud)

UPD:tsconfig.json.添加了typeRoots选项.

现在得到新的错误:

ERROR in .../node_modules/@types/angularjs/angular-mocks.d.ts(6,26):error TS2307:找不到模块'angular'.

ERROR在.../node_modules/@types/angularjs/angular-mocks.d.ts(65,49):错误TS2304:找不到名称'IServiceProvider'.

ERROR在.../node_modules/@types/angularjs/angular-mocks.d.ts(122,62):错误TS2304:找不到名称'IScope'.

ERROR在.../node_modules/@types/angularjs/index.d.ts(66,43):错误TS2304:找不到名称'JQuery'.

Zho*_*ian 5

如果你在命令行中运行它应该解决问题.

npm install @types/angular
Run Code Online (Sandbox Code Playgroud)

令人烦恼的是这个修复是由于某种原因它不会更新你的package.json ..但是如果你将以下内容添加到package.json 中的依赖项而不是上面它应该修复问题并拥有package.json镜像你的包裹.

"@types/angular": "1.6.5",
"@types/jquery": "2.0.40",
Run Code Online (Sandbox Code Playgroud)

  • `由于某种原因它不会更新你的package.json` - 添加`--save`标志以便将它保存在你的package.json中 (7认同)
  • 从npm5开始,npm默认为--save。 (2认同)