TypeScript:使用 TypeScript 和 webpack 2 解析 TypeAhead.js



我从webpack收到以下错误。

错误 in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts 找不到模块: 错误: 无法解析 中的"提前键入" ...

我安装了以下内容

npm install typeahead.js
npm install @types/typeahead

我的打字稿如下,使用node模块分辨率。

import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.
class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}

这将生成如下 JavaScript:

"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...

My webpack.config.js 如下:

module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /.ts$/, use: 'ts-loader' }
        ]
    }
};

导入到吞噬任务中。

如何指定typeahead位于node_modules/typeahead.js/dist/typeahead.bundle.js

模块称为typeadhead.js因此您还需要导入typeahead.js,而不是typeahead

import "typeahead.js";

导入始终与使用 npm 安装它时使用的名称相同。它甚至并不特别,它只是简单地查看node_modules并找到具有给定名称的目录。然后,它会查看package.json并导入main字段中指定的文件。另请参阅节点.js - 作为模块的文件夹。

您可以使用resolve.alias来更改导入的名称,但在这种情况下,这样做并没有很好的理由。

我通过进行以下更改来解决此问题。

您需要分别导入寻血猎犬和 Typeahead。为此,请编辑您的webpack.config.js

  resolve: {
    extensions: ['.js', '.ts'],
    alias: {
      typeahead: 'corejs-typeahead/dist/typeahead.jquery.min.js',
      bloodhound: 'corejs-typeahead/dist/bloodhound.min.js'
    }
  },

然后在您的.ts文件中:

import "typeahead";
import * as Bloodhound from "bloodhound";

您可以使用别名来解决此问题。在webpack.config.js中更改内容的最小示例:

module.exports = {
  /* ... everything you currently have */
  resolve: {
    alias: {
      typeahead: 'typeahead.js'
    }
  }
}

最新更新