首页 > 解决方案 > Bootstrap 4 TypeScript 类型定义无法编译 - 找不到模块'popper.js'

问题描述

我正在尝试设置一个 TypeScript 项目并让 bootstrap 4 与Visual Studio Code 中的PopperjQueryKnockout一起工作。

我安装了敲除、jquery 和引导类型定义,

npm install -–save @types/knockout
npm install -–save @types/jquery
npm install --save @types/bootstrap

在 require.js 配置中引用了 JS 文件

declare var require: any;
require.config({
    paths: {
        "knockout": "externals/knockout-3.5.0",
        "jquery": "externals/jquery-3.3.1.min",
        "popper.js": "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js",
        "bootstrap": "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    }
})

tsconfig.json的是这样的:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": { 
            "*": ["types/*"] 
        },
        "outDir": "./built/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "amd",
        "target": "es5"
    },
    "files":[
        "src/require-config.ts",
        "src/hello.ts"
    ]
}

我去编译项目,我得到以下错误:

node_modules/@types/bootstrap/index.d.ts:9:25 - error TS2307: Cannot find module 'popper.js'.

9 import * as Popper from "popper.js";
                          ~~~~~~~~~~~

Found 1 error.

The terminal process terminated with exit code: 1

我的 Bootstrap 类型定义文件似乎无法编译,因为它找不到 popper.js 模块。

popper.js 模块我的@types 文件夹中

node_modules
 |-@types
 |  |- bootstrap
 |     |-index.d.ts (this is failing)
 |- popper.js
    |- index.d.ts (popper.js type definition)

我如何告诉 TypeScript 编译器引导类型定义正在寻找的 popper.js 位于层次结构中的较高位置?

即使接近这个,我也找不到任何答案。因此,要么我偶然发现了一个其他人从未遇到过的错误(不太可能),要么是 Typescript 的新手,我没有正确设置我的环境并且错过了其他人都得到的非常基本的设置步骤,因此没有人曾经遇到过不得不问(很可能)。

我能做些什么来解决这个问题?

标签: typescriptcompiler-errorsbootstrap-4popper.jstype-definition

解决方案


两种选择:

  • 删除"module": "amd"配置选项或
  • 添加"moduleResolution": "node"选项。

第二个选项如下所示:

"moduleResolution": "node",
"module": "amd",

为什么这些选项有效?

简而言之,当我们使用amd模块时,默认的模块解析策略是Classic而不是Node。两者之间的重要区别在于Node 策略将目录名称识别为模块,而 Classic 策略则没有。

这里有更多关于模块解析策略的信息。


推荐阅读