如何将typescript npm模块导入语法转换为ECMA2015模块导入语法

Nat*_*rty 8 typescript rollupjs typescript-typings es6-modules

我正在尝试在Typescript项目中使用第三方库(特别是三个).作为概念验证,我正在尝试将所有客户端代码解析为模块(无需转换为ES5或捆绑).

我的项目设置如下:

cgi/app.js (compiled typescript file)
node_modules/@types
node_modules/three/build/three.module.js
src/app.ts
index.html
tsconfig.json
package.json
Run Code Online (Sandbox Code Playgroud)

在我的 index.html

<head>
    <script type="module" src="node_modules/three/build/three.module.js"></script>
    <script type="module" src="cgi/app.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用typescript解析three.module.js文件,同时还使用来自的类型声明@types/three.通常,您可以使用以下内容导入库:import { Scene } from 'three'这为我提供了类型支持,但编译后的模块没有正确的ES6语法.它需要import { Scene } from './path/to/three.js.

不幸的是,typescript 不支持自动执行此操作.我可以直接导入ES6模块(不使用@types)但是我失去了类型支持.

postcriptcript编译,是否可以将模块分辨率从节点语法转换为ES6语法?(例如import { Scene } from 'three'转换为import { Scene } from './three.js'

具体来说,是否可以利用汇总来实现这一目标?

Nat*_*rty 1

这可以使用 Rollup 的配置值来完成paths

例如,在我的app.ts文件中,我有一个标准的 npm-style-import:

import { somedependency } from my-dependency(其中my-dependency是节点模块,例如three。)

在该rollup.config文件中,您需要告诉 Rollup 该文件的路径:

output: { ... },
plugins: [ ... ]
paths: {'my-dependency': './your/web/path/to/the/dependency.js'}
Run Code Online (Sandbox Code Playgroud)

您编译的包现在可以很好地导入浏览器可以理解的代码。