在 Namespaced Typescript 项目中使用 NPM 模块

use*_*413 5 typescript reactjs react-redux typescript-typings typescript2.0

我有一个项目(现有项目),其前端是用命名空间打字稿编写的。我无法从命名空间方法重写所有打字稿文件以导出/导入 es6 语法。

但是下面的代码工作正常。如果我添加我的新 ts 模块或反应组件没有问题,只要我将它包装在命名空间中并按类或命名空间前缀调用它,如果它在其他命名空间中。

问题是我不能使用带有 import 语句的外部模块。我该如何使用..?因为 import 语句抛出错误。

为了更具体地说明下面的代码,我想使用 react-redux,

当我检查 node_moduels 文件夹时,我看到了 @types 文件夹,从那里引用了 React 名称空间我假设由于 tsconfig 中的这一行

"typeRoots": [
      "./node_modules/@types/"
    ]
Run Code Online (Sandbox Code Playgroud)

但是当我安装npm install --save @types/react-redux它时,它也在节点模块的@types 文件夹下创建了带有 index.ts 的 react-redux 文件夹。但它没有命名空间导出行,React 类型文件如何具有如下所示的内容。

export as namespace React;

declare namespace React {
....
}
Run Code Online (Sandbox Code Playgroud)

最终..如何在这个项目中使用第三方节点模块,尤其是 react-redux。或任何简单的节点模块,并在任何 ts 文件中访问它简单的模块,例如“react-bootstrap” 下面是包装在命名空间中的反应组件的简单 ts 文件,该文件工作正常(import staement 除外)

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>

            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的 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/"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道命名空间不是推荐的方法。但这是一个现有项目,不能将命名空间中的所有文件重写为导入/导出语句。

Pet*_*rdt 6

好的,让我们一步一步让它可运行:

  1. 尽管您没有明确说明,但我假设您收到了错误消息Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'.。该选项outFile生成一个主文件,其中连接了所有代码。由于使用的是"target": "es5"在你的tsconfig.json,默认值modulecommonjscommonjs是 node.js ( var x = require('x')/ exports.x = x)广泛使用的模块语法,该语法不支持将代码合并到一个文件中,因此被禁止。但是你想在浏览器中使用你的代码,所以commonjs无论如何都不支持。所以首先要做的是

    插入"module": "AMD"到您的tsconfig.json文件中。

    AMD 是一种可在浏览器中使用的模块语法。您也可以使用"UMD",它只是一个扩展,以便模块支持AMDcommonjs模块。

  2. 为了避免以后进行更多配置,您还应该

    在您的文件中更改"outFile": "wwwroot/Scripts/site/Profiles.js"为。"outDir": "wwwroot/Scripts/site"tsconfig.json

  3. 设置moduleAMD更改moduleResolutionfrom的默认值nodeto classic,但这并不好,因为 thenimport {createStore} from 'redux'将失败并显示错误消息Cannot find module 'redux'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?。所以

    包含"moduleResolution": "node"到您的tsconfig.json文件中。

  4. 在您的代码中,您定义了一个扩展另一个基类的类。如果您转译此继承,__extends则需要一个特殊函数。使用当前设置,此函数不是由打字稿生成的,您会收到错误消息Uncaught ReferenceError: __extends is not defined。所以

    删除"noEmitHelpers": true

  5. 现在您的所有文件都可以转换为 AMD 模块。但是要使用这些模块,您需要一个模块加载器。最流行的一种是require.js。要使用它,

    插入<script data-main="setup" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>到您的 HTML 文件中。

    您也可以下载它并自己提供服务。data-main="setup"意味着在 require.js 被加载后,脚本setup.js被执行。此脚本在下一步中创建。

  6. require.js 需要一些配置才能找到所有模块。所以

    创建wwwroot\Scripts\site\setup.js

    requirejs.config({
      appDir: ".",
      paths: { 
        'react': ['./node_modules/react/umd/react.production.min.js', 'https://unpkg.com/react@16/umd/react.production.min'],
        'react-dom': ['./node_modules/react-dom/umd/react-dom.production.min.js', 'https://unpkg.com/react-dom@16/umd/react-dom.production.min'],
        'redux': ['./node_modules/redux/dist/redux.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min'],
      },
    });
    
    requirejs(['entryPoint'], function() {
      console.log("Entry point 'index' has been loaded!");
      return {};
    });
    
    Run Code Online (Sandbox Code Playgroud)

    在第一部分中配置了 require.js。特别是,npm定义了外部模块(通过 安装的模块)的位置。此处reactreact-domredux的位置设置为node_modules文件夹中的位置,其中包含来自内容交付网络 (CDN) 的外部文件作为备份。您还可以删除其中一个位置。他们从左到右请求,如果一个请求失败则继续。如果您使用node_modules文件夹中的位置,您也必须从您的网络服务器提供它们!

    在第二部分entryPoint中执行模块。这是您的应用程序的入口点。将名称更改为您想要作为入口点的任何名称。如果您希望文件中定义的模块someOtherFile.js作为入口点,则编写requirejs(['someOtherFile'], ....

  7. 要转译所有文件,请运行

    tsc --project tsconfig.json.

  8. 提供目录中的所有文件,wwwroot/Scripts/site包括您的 HTML 文件。出于测试目的,您可以使用

    npx serve.

你可以在这里看到稍微修改过的代码:https : //codesandbox.io/s/elated-fermat-ie2ms?file=/src/index.tsx