【问题标题】:How to convert typescript npm module import syntax to ECMA2015 module import syntax如何将 typescript npm 模块导入语法转换为 ECMA2015 模块导入语法
【发布时间】:2018-11-01 20:08:01
【问题描述】:

我正在尝试在 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

在我的index.html

<head>
    <script type="module" src="node_modules/three/build/three.module.js"></script>
    <script type="module" src="cgi/app.js"></script>
</head>

我正在尝试让 typescript 解析 three.module.js 文件,同时还使用来自 @types/three 的类型声明。通常,您会使用以下命令导入库:import { Scene } from 'three',这给了我类型支持,但编译后的模块没有正确的 ES6 语法。必须是import { Scene } from './path/to/three.js

不幸的是,打字稿does not support doing this automatically yet。我可以直接导入 ES6 模块(不使用 @types),但是我失去了类型支持。

打字稿编译后,是否可以将模块解析从节点语法转换为 ES6 语法? (例如,import { Scene } from 'three' 转换为 import { Scene } from './three.js'

具体来说,是否可以利用汇总来完成此任务?

【问题讨论】:

    标签: typescript typescript-typings es6-modules rollupjs


    【解决方案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'}
    

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

    【讨论】:

      猜你喜欢
      • 2014-04-29
      • 2022-01-20
      • 2015-07-27
      • 1970-01-01
      • 2019-07-06
      • 2016-05-22
      • 2021-01-05
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多