简体   繁体   English

在 React Typescript 项目中使用来自 JS 库的 window object

[英]Use window object from JS lib in React Typescript project

Having a fresh new project in React and Typescript, I need to use a JS Lib developed by my fellow colleagues.在 React 和 Typescript 中有一个全新的项目,我需要使用我的同事开发的 JS Lib。

The lib is packaged and added to the project with NPM.该 lib 被打包并添加到项目中,使用 NPM。 The content of the min.js is like: min.js 的内容如下:

window.SharedObj=function(e){
...
}

So, this lib is designed to register an instance of SharedObj at the window scope, and I need to retrieve this instance in my top level component (index.tsx).因此,此库旨在在 window scope 注册 SharedObj 的实例,我需要在我的顶级组件 (index.tsx) 中检索此实例。

I've successufully done it this way:我已经成功地这样做了:

require('path/lib.min.js');

// @ts-ignore
new SharedObj();

if ((window as any).SharedObj) {
    ReactDOM.render(
        <React.StrictMode>
            <App/>
        </React.StrictMode>,
        document.getElementById('root')
    );
}

This works, but it seems wrong to me to ts-ignore and "as any" in order to make this work.这行得通,但我认为 ts-ignore 和 "as any" 来完成这项工作似乎是错误的。

Do you have a better solution?你有更好的解决方案吗? May I extend the Window definition?我可以扩展 Window 定义吗?

You can declare the Window object globally as an interface with SharedObj being one of it's property.您可以将Window object 全局声明为接口,其中SharedObj是其属性之一。

declare global {
  interface Window {
    // you'll need to explicitly specify the
    // type of arguments & function return type
    SharedObj: (e: ArgsType) => ReturnType;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法从“screens\SignUpScreen.js”解析“react-native-paper/lib/typescript/src/components/MaterialCommunityIcon” - Unable to resolve "react-native-paper/lib/typescript/src/components/MaterialCommunityIcon" from "screens\SignUpScreen.js" 无法在 JS 中使用来自 TypeScript 的“接口”声明(React Native 测试) - Cannot use "interface" declarations from TypeScript in JS (React Native tests) 通过Webpack从打字稿中导出对象并在JS中使用它 - Export object from typescript through webpack and use it in JS React js - 无法使用反应图标,找不到模块'../lib' - React js - Unable to use react-icons, Module not found '../lib' 从没有 .d.ts 的打字稿文件中调用 Js lib - Call Js lib from typescript file withou .d.ts 如何使用React Native项目中的香草JS文件? - How to use vanilla JS files from a React Native project? 使用 typescript 中的 javascript 库(具有继承的 javascript 依赖项) - Use javascript lib from typescript (with inherited javascript dependencies) 无法在 Typescript 组件中使用 JS 反应挂钩 - Cannot use JS react hook in Typescript component 无法从&#39;ReactTestUtils.js&#39;找到模块&#39;react / lib / React&#39; - Cannot find module 'react/lib/React' from 'ReactTestUtils.js' 使用来自 react 打字稿项目的 @wdio/sync - Using @wdio/sync from a react typescript project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM