【问题标题】:Persuading webpack to use node_modules/@types说服 webpack 使用 node_modules/@types
【发布时间】:2017-04-16 06:56:27
【问题描述】:

我正在尝试使用 Typescript 2、Webpack 和 Angular 1.5,但是在构建 Webpack 时一直抱怨它:

无法解析 C:\play\gt\src 中的模块“@types/angular”

我被难住了。一直在谷歌上搜索并搞砸,但无处可去。

我的 app.ts 看起来像:

import * as angular from "@types/angular";
let app = angular.module ("GT.module", []);

我的 tsconfig 看起来像:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "typeRoots" : [
        "node_modules/@types"
      ]
  },
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ],
  "include" : [
    "src/**/*"
  ]
}

...最后是 webpack 配置:

module.exports = {
        entry: './src/app.ts',
        output: {
            filename: './dist/app.js'
        },
        devtool: "source-map",
        resolve: {
            extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
            modulesDirectories: ["node_modules"]
        },
        module: {
            loaders: [
                { test: /\.ts$/, loader: 'ts-loader' }
            ]
        }
    }

【问题讨论】:

    标签: angularjs typescript webpack


    【解决方案1】:

    @types 不是您可以导入的模块,它们是供编译器引用的类型定义。

    @types/angular 包实际上并没有实现.module 并且您的代码将会中断(如果它曾经编译过)。

    你可能想做一些类似的事情:

    /// <reference path="../node_modules/@types/angular/index.d.ts" />
    import * as angular from "angular";
    let app = angular.module ("GT.module", []);
    

    但是,您通常甚至不需要reference,因为编译器会自动包含来自@types/* 包的typedef,除非您告诉它不要(通过设置types 或@ 987654328@ 在您的tsconfig.json)。此行为是在 v2 中添加的,并且是相当新的。

    【讨论】:

      【解决方案2】:

      您的目录树是什么样的? 它应该是这样的:

      node_modules/
         @types/
            angular/
      src/
      tsconfig.json
      webpack.config.js
      

      那你就不需要"typeRoots" : ["node_modules/@types"]

      import * as angular from "@types/angular"; 应该变成import * as angular from "angular";

      Typescript 编译器 2.0 将知道在哪里寻找正确位置的类型(即:node_modules/@types

      【讨论】:

      • 谢谢!那已经解决了。 Typescript 目标帖子似乎在不断变化,很难找到最新的文章。
      • 是的,我知道,javascript 生态系统发展很快,试试官方文档,它维护得很好。例如,此链接将使用 typescript 包装 webpack:typescriptlang.org/docs/handbook/react-&-webpack.html
      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 2017-02-19
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2017-02-06
      • 2022-12-16
      相关资源
      最近更新 更多