简体   繁体   English

react-native - * .js导入* .ts文件

[英]react-native - *.js importing *.ts file

How to allow *.js files to import *.ts files in react-native but without rename of any of two files ? 如何允许*.js文件以react-native方式导入*.ts文件但不重命名任何两个文件

we want to import below src/lib/setGlobalStyle .ts file from the src/App .js 我们想从src/App .js导入src/lib/setGlobalStyle .ts文件下面

//MIT LICENSE from: https://github.com/Ajackster/react-native-global-props

import React from 'react'
import { StyleProp, ViewStyle } from 'react-native'


export function setGlobalStyle(obj, customProps) {
 const oldRender = obj.prototype.render;
  const initialDefaultProps = obj.prototype.constructor.defaultProps;
  obj.prototype.constructor.defaultProps = {
    ...initialDefaultProps,
    ...customProps,
  }
  obj.prototype.render = function render() {
    let oldProps = this.props;
    this.props = { ...this.props, style: [customProps.style, this.props.style] };
    try {
      return oldRender.apply(this, arguments);
    } finally {
      this.props = oldProps;
    }
  };
}

but below import which is inside App .js only works when we rename the setGlobalStyle .ts file to setGlobalStyle .js : 但低于进口是内部App .js文件只有当我们重命名工作setGlobalStyle 的.ts文件到setGlobalStyle .js文件

import * as Utils from './lib/setGlobalStyle'

and of course the setGlobalStyle .ts currently does not contain any TypeScript types, that is because we had to remove all and rename it to .js so we can continue on the project until this gets an answer. 当然, setGlobalStyle .ts当前不包含任何TypeScript类型,这是因为我们必须删除所有并将其重命名为.js,以便我们可以继续该项目,直到得到答案。

note : the reason why we need TypeScript is to allow IDE autocomplete of the parameters (ie the customProps argument). 注意 :我们需要TypeScript的原因是允许IDE自动完成参数(即customProps参数)。

JSDoc-support in Javascript allows you to import type definitions directly. Javascript中的JSDoc支持允许您直接导入类型定义。 I know that's not the same as importing the actual module (but I think that is madness if the type definitions exist): 我知道这与导入实际模块不同(但如果存在类型定义,我认为这很疯狂):

/**
 * @param {import("./mymodule").customProps } customProps
 */
export function setGlobalStyle(obj, customProps) {
    customProps. // has full auto-completion 

在此输入图像描述

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

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM