【问题标题】:typescript: resolving typeahead.js with typescript and webpack 2typescript:使用 typescript 和 webpack 2 解析 typeahead.js
【发布时间】:2017-08-21 21:52:35
【问题描述】:

我从 webpack 收到以下错误。

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

我的 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


    【解决方案1】:

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

    您需要分别导入 Bloodhound 和 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";
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 它解决了部分问题,typeahead.js 文件在组件使用后包含在输出中,因此整个导入仍然中断,需要我手动包含 typeahead.js 文件无论如何。
      【解决方案3】:

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

      import "typeahead.js";
      

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

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

      【讨论】:

      • 这不起作用,只要我将import "typeahead" 更改为import "typeahead.js",打字稿编译器就会失败并显示property typeahead does not exist on type JQuery,正如我在问题中解释的那样,导入是必要的,因为类型定义在 typeahead 中,而不是 typeahead.js
      • 另外,如果我使用import "typeahead.js",webpack 会将文件包含在输出中,但变量Bloodhound 未定义,因此虽然文件包含在输出中,但其中的类型是无法在 javascript 中访问。
      猜你喜欢
      • 2017-04-26
      • 2018-02-17
      • 2016-11-10
      • 2017-06-14
      • 1970-01-01
      • 2017-07-04
      • 2017-09-21
      • 2019-03-15
      相关资源
      最近更新 更多