【问题标题】:How do I import libraries in TypeScript in general?一般如何在 TypeScript 中导入库?
【发布时间】:2021-05-30 20:02:54
【问题描述】:

我是 TypeScript 的新手,只是在钻研那个兔子洞。我想,到目前为止我理解了这个概念,但我不明白的是我最终是如何使用库的(在我的例子中,D3 用于操作 SVG DOM)。在 vanilla Javascript 中,我只是通过一个又一个地包含库和我的 main.js 脚本来以老式方式完成它,但是随着我的项目的增长,我想通过模块化方法来使用 TypeScript 的优势。

当前问题是这个浏览器错误(Chrome):

未捕获的类型错误:无法解析模块说明符“d3”。相对引用必须以“/”、“./”或“../”开头

嗯,我知道它指向我的导入语句,但我不知道如何解决它。

tsconfig.json

    {
        "compilerOptions": {
            "target": "ES5",'ESNEXT'. */
            "module": "ESNext",
            "declaration": true,
            "outDir": "./dist/fgn/",
            "rootDir": "./src/fgn/",
            "strict": true,
            "allowSyntheticDefaultImports": true,
            "esModuleInterop": true,
            "skipLibCheck": true, // required to avoid checking d3 type definitions
            "forceConsistentCasingInFileNames": true
        }
        // ,"files": [],
        // "include": [],
        // "exclude": []
    }

index.html(摘录)

    <head>
        <script src="../dist/fgn/fgn.js" type="module"></script>
    </head>
    <body>
        <button id="testButton" onClick="unreachableFoo();">Test Script</button>
    </body>

./src/fgn/fgn.ts

    /*  Assuming I want to use the whole library. That's how it is documented by Mike Bostock.
        However, this import statement throws an error in the browser (tested in Chrome, Firefox)
        when being transpiled to javascript */
    import * as d3 from "d3"; // points to '[root]/node_modules/@types/d3' (index.d.ts)

    console.log('script is running...');

    // This is the desired functionality I want to gain: having access to d3 from global namespace (globalThis ?)
    d3.select('#testButton').on('click', () => {alert('button clicked!');});

    // Also this is not working. The browser complains the function is not defined.
    function unreachableFoo() { console.log('foo'); }

我尝试了多个 tsconfig 设置并将导入更改为指向“[root]/node_modules/d3/”(index.js),同时在 tsconfig 中启用“allowJs”,但这导致了进一步的问题,因为 tsc 以某种方式包含了node_modules/@types/ 路径导致声明文件混乱和错误。

另一个尝试是使用 webpack,设置 package.json 并从那里构建依赖项。也许我在正确的轨道上,但浏览器错误仍然存​​在。

我错过了什么?

【问题讨论】:

标签: javascript typescript tsconfig tsc


【解决方案1】:

欢迎! D3 文档会有点难以理解,因为它使用的是 JS 的 import 语句而不是 TS。尝试将您的导入语句切换为

import { *desired methods* } from 'd3'; // there is no default d3 export

您还需要撤消对 tsconfig 的更改。

【讨论】:

  • 谢谢!这还没有解决问题,但我越来越近了。我现在把它改成了import {select} from 'd3';。该文档link 也有帮助。您明确表示哪些撤消? "module": "commonjs"?我收到另一个错误,即输出 js 文件Object.defineProperty(exports, "__esModule", { value: true }); 中未定义“导出”。最后我在@types/d3/index.d.ts 文件中发现了这一行export as namespace d3;,这就是为什么我认为我可以简单地使用import * as d3 from 'd3' 使用它d3.select()
  • 它与 React 中完全相同的导入调用一起工作,但我不知道幕后发生了什么。
  • 我没有对您的 tsconfig 进行任何具体更改,只是想解释一下确实不需要任何更改。我确实玩得更多,并意识到您的 tsconfig 中有 rootDiroutDir,当我为 React 和 D3 启动一个快速项目时,这两个项目都不在我的 tsconfig 中。添加了rootDir,它立即开始为我抛出一些错误(尽管与您的不同)。然后我删除了 tsconfig 中的所有内容,重新启动了项目,它添加了项目所需的所有内容。
【解决方案2】:

知道了,

我只是错过了 browserify 的步骤。我现在使用的是 Rollup,而不是 webpack。对于在开始学习该主题时遇到类似困难的任何人,这里有一些很好的解释(花时间去理解每一个):

How to Setup a TypeScript project using Rollup.js -- Rollup 安装和所需的 tsconfig.json 设置;不过,并非所有建议的安装都是必需的。

Missing global variable names #162 -- rollup.config.js 设置

@rollup/plugin-node-resolve -- 另外这个插件的用法

Official rollup.js documentation -- RTFM

但是,rollup.config.js 中的 Rollup 特定字段随着时间的推移发生了变化,例如'entry' 属性被重命名为 'input'。这是我按照上述教程进行的当前配置:

/* buil-in */
import resolve from '@rollup/plugin-node-resolve';
/*  Install both plugins:
    npm i @rollup/plugin-babel @rollup/plugin-commonjs --save-dev
*/
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';

export default [
    {
        input: 'src/scripts/main.js', // change this accordingly
        plugins: [
            resolve({
                jsnext: true,   
                main:   true,
                browser:true,         
            }),
            commonjs(),
            babel({
                exclude: 'node_modules/**',
            })
        ],
        output: {
            name: 'main',
            file: 'public/scripts/main.js', // change this accordingly
            /*  format: 'iife' wraps everything into a self-executing function
                (function () { ... }());
            */
            format: 'iife' // or 'cjs'
        }
    }
];

不过,这还没有缩小代码。这只是一个开发设置,但您也可以添加一个生产设置。

package.json 构建脚本

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc -b && rollup -c rollup.config.js"
  }

【讨论】:

    猜你喜欢
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2020-06-25
    • 2020-07-21
    • 1970-01-01
    • 2022-10-21
    相关资源
    最近更新 更多