typescript:使用typescript和webpack 2解析typeahead.js

问题描述 投票:0回答:3

我从webpack收到以下错误。

错误:./wwwroot/js/admin/infrastructure/typeaheadComponent.ts找不到模块:错误:无法在...中解析'typeahead'

我安装了以下内容

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 () { ...

我的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' }
        ]
    }
};

导入到gulp任务中。

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

javascript typescript webpack webpack-2
3个回答
0
投票

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

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

0
投票

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

import "typeahead.js";

导入始终与用于使用npm安装它的名称相同。它甚至不是特别的,它简单地查看node_modules并找到具有给定名称的目录。然后它查看package.json并导入main field中指定的文件。另见Node.js - Folders as Modules

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


0
投票

我通过进行以下更改解决了这个问题。

您需要单独导入Bloodhound和Typeahead。为此,请编辑你的qazxsw poi

webpack.config.js

然后在你的 resolve: { extensions: ['.js', '.ts'], alias: { typeahead: 'corejs-typeahead/dist/typeahead.jquery.min.js', bloodhound: 'corejs-typeahead/dist/bloodhound.min.js' } }, 文件中:

.ts
© www.soinside.com 2019 - 2024. All rights reserved.