【发布时间】:2021-01-22 07:40:24
【问题描述】:
我有一个项目(现有项目),其前端是用命名空间打字稿编写的。 我无法将所有打字稿文件从命名空间方法重写为导出/导入 es6 语法。
但是下面的代码运行良好。如果我添加我的新 ts 模块或反应组件,我将它包装在命名空间中并通过类或命名空间前缀调用它,如果它在其他命名空间中,则没有问题。
问题是我不能使用带有 import 语句的外部模块。我该如何使用..?因为 import 语句抛出错误。
为了更具体地了解下面的代码,我想使用 react-redux,
当我检查 node_moduels 文件夹时,我看到了引用 React 命名空间的 @types 文件夹 我假设由于 tsconfig 中的这一行
"typeRoots": [
"./node_modules/@types/"
]
但是当我安装npm install --save @types/react-redux 时,它还在节点模块的@types 文件夹下创建了带有index.ts 的react-redux 文件夹。但它没有命名空间导出行,React 类型文件如何具有以下内容。
export as namespace React;
declare namespace React {
....
}
最终..我如何在这个项目中使用第三方节点模块,尤其是 react-redux。 或任何简单的节点模块并在任何 ts 文件简单模块中访问它,例如“react-bootstrap” 下面是包含在命名空间中的反应组件的简单 ts 文件,它工作正常(导入状态除外)
import { createStore } from 'redux'; //if i add this line this is throwing error.
namespace Profile.Sample {
import { createStore } from 'redux'; //this too throwing error, without these lines my code is working fine.
export class Profiles extends React.Component<any> {
constructor(props) {
super(props);
this.state = { brand: "Ford" };
}
render(): React.ReactNode {
return (
<sect
<div className="container-fluid">
<div className="row">
<div className="col-lg-12">
<div className="main-title">
<h2>Profiles</h2>
<p>Lorem ipsum dolor sit amet, consectetur adi</p>
</div>
</div>
</div>
</div>
</section>
);
}
}
}
下面是我的 tsconfig
{
"compileOnSave": true,
"compilerOptions": {
"preserveConstEnums": true,
"experimentalDecorators": true,
"declaration": true,
"emitBOM": true,
"jsx": "react",
"noEmitHelpers": true,
"inlineSourceMap": true,
"inlineSources": true,
"outFile": "wwwroot/Scripts/site/Profiles.js",
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"target": "es5",
"typeRoots": [
"./node_modules/@types/"
]
}
}
我知道命名空间不是未来推荐的方法。但这是一个现有项目,无法将命名空间中的所有文件重写为导入/导出语句。
【问题讨论】:
-
您是否将您的代码与任何捆绑程序捆绑在一起——webpack、rollup、parcel?
-
不,只是build js在项目主文件中作为脚本调用
-
tsconfig.json文件是固定的还是可修改的? -
它可以修改..但现有代码不应该破坏。
标签: reactjs typescript react-redux typescript-typings typescript2.0