目前正在将我的 javascript 应用程序翻译为 typescript。以前我只是使用
m()
和 Vnode
没有任何导入,但打字稿需要包含 import m, { Vnode } from 'mithril';
所以它知道它们是什么。
问题是,当编译时,它会将
import m from 'mithril';
添加到新 js 文件的顶部。由于某种原因,导入会破坏应用程序。我不完全确定在没有导入的情况下它如何工作,或者为什么导入会破坏它。这是针对 chrome 扩展的,错误日志记录非常没有帮助,所以我什至不知道具体的错误是什么。该应用程序只是白屏。
目前我正在尝试通过编写一个脚本来解决这个问题,该脚本只是从每个文件中删除该导入,但我想知道是否有一种方法可以首先忽略该导入/不让它破坏 javascript。
您可以使用
declare
告诉 TypeScript 全局空间中预先存在的 m
引用(因此它也可以通过例如 window.m
获得),并使用 typeof
绑定导入的类型对它:
// Typescript-only import
import type mithril from 'mithril'
// Typescript-only reference declaration and binding to said types
declare global {
var m: typeof mithril
}
// Usage example
interface LinkAttrs {
url: string
}
// Types referenced via `mithril` namespace
const Link: mithril.Component<LinkAttrs> = {
view: ({attrs}) =>
m('a', {href: attrs.url})
}
// `m` used as normal with full type hinting & enforcement
m.render(document.body, m(Link, {url: 'http://stackoverflow.com'}))
我在各个地方读到可以在项目根目录中的
global.d.ts
中声明项目全局变量,但我无法完成这项工作,还没有找到关于此的规范文档。
只需放置即可解决此问题
declare let m: any;
在我的文件顶部,希望我使用正确。这满足打字稿并且不会被翻译成 JS
这不是一个理想的解决方案,所以我目前正在做的是将这一行添加到
find . -type f -name '*.js' -print0 | xargs -0 sed -i '' '/import m from/d'
这可以有效地查找并删除每个秘银导入