【问题标题】:What is the current way to import 3rd party JS node modules for the browser?当前为浏览器导入 3rd 方 JS 节点模块的方法是什么?
【发布时间】:2016-05-12 19:55:03
【问题描述】:

关于这个话题有很多问题和答案,但我似乎找不到最新的答案。

我想使用本地安装在 node_modules 中的模块hyperscript。它没有 d.ts 文件。

我可以创建一个,我认为应该如下所示:

declare module 'hyperscript' {
    export default function H(...a: any[]) : HTMLElement;
}

我把它放在 src/typings/hyperscript.d.ts 中,打字稿似乎可以接受。

我的ts源文件有:

import H from 'hyperscript';

const element = H('h1', "This is a title");

我编译和捆绑:

browserify --debug src/main.ts -p [ tsify --noImplicitAny ] > js/bundle.js

一切顺利,但是当我尝试在浏览器中运行时,我得到:

Uncaught TypeError: hyperscript_1.default is not a function

我很确定超脚本只输出一个默认函数,因为在带有 babel/browserify 的普通 JS 中,我使用:

import H from 'hyperscript';

而且效果很好。

我的 package.json 看起来像:

{
  "name": "hyperscript-example-ts",
  "version": "1.0.0",
  "description": "hyperscript typescript example",
  "author": "Me",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "hyperscript": "latest"
  },
  "devDependencies": {
    "browserify": "latest",
    "tsify": "latest",
    "uglifyjs": "latest"
  },
  "scripts": {
    "build": "browserify --debug src/main.ts -p [ tsify --noImplicitAny ] > js/bundle.js"
  }
}

我的 tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "allowJs": true,
        "declaration": false,
        "noImplicitAny": true,
        "removeComments": false,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "outDir": "js",
        "sourceMap": true,
        "watch": false
    },
    "filesGlob": [
        "src/**/*.ts",
        "src/typings/**/*.d.ts",
        "!./node_modules/**/*.ts"
    ],
    "atom": {
        "rewriteTsconfig": false
    }
}

非常感谢任何帮助!

编辑:再多做一些,看起来唯一的方法是将我的导入重写为:

/// <reference path="./typings/hyperscript.d.ts" />
import _H = require('hyperscript'); // Gets no type info from my d.ts file
const H: (...a: any[]) => HTMLElement = _H as any;

TypeScript 手册说我应该能够将标准导入语法与 3rd 方 JS node_modules 一起使用。引用this page:

/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");

【问题讨论】:

    标签: typescript


    【解决方案1】:

    声明文件基本上是开发人员试图向 TypeScript (more) 解释环境世界

    在你的情况下声明:

    declare module 'hyperscript' {
        export default function H(...a: any[]) : HTMLElement;
    }
    

    实际上是错误的。函数H 不是默认 导出。它是主要的出口。所以你真正想要的是:

    declare module 'hyperscript' {
        export = function H(...a: any[]) : HTMLElement;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2017-11-17
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多