3

サードパーティ ライブラリを必要とする TypeScript モジュールを作成しました。

import Dexie from "dexie";

namespace storage {
  ...
}

TypeScript ファイルをコンパイルすると、次の JavaScript 出力が得られます。

"use strict";
var dexie_1 = require("dexie");
var storage;
(function (storage) {
  ...
})(storage || (storage = {}));

Node.js 環境で出力を使用する場合、これで問題ありません。しかし、ブラウザで使用するために、 をlike:var dexie_1 = require("dexie");のオブジェクトに置き換えたいと思います。windowvar dexie_1 = window.Dexie;

コンパイルした JS のステートメントを(グローバル名前空間)requireのオブジェクトに置き換えることはできますか? windowGulp プラグインまたは sth はありますか。周りが似てる?

私のtsconfig.jsonはこれです:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}
4

2 に答える 2

3

インポートをウィンドウ オブジェクトに置き換えるには?

不可能です。次の 2 つのオプションがあります。

グローバル オブジェクトを使用する

ブラウザでは、オブジェクトが によってロードされる<script>と、コードはそれをグローバル変数として使用します。TypeScript では、グローバル宣言ファイルを使用する必要があります。ここではモジュールを使用しないので、何もimportする必要はありません。

バンドラーまたはローダーを使用する

Webpackなどのバンドラーを使用できます。またはSystemJSのようなローダー

于 2016-07-11T07:34:15.227 に答える
3

Webpackは にマップできrequire("dexie");ますwindow.Dexie

webpack.config.jsで次のように宣言するだけです。

module.exports = {
  externals: {
    'dexie': 'Dexie'
  }
};

完全を期すために、最小限の作業例を次に示します。

ディレクトリ レイアウト:

  • bower_components ( のディレクトリbower install)
  • dist (からのディレクトリgulp default)
  • node_modules ( のディレクトリnpm install)
  • src (TypeScript ソースコードのディレクトリ)
  • タイピング ( のディレクトリtypings install)
  • bower.json (フロントエンドの依存関係)
  • gulpfile.js (ビルド構成)
  • index.html (webpack コードをテストするためのデモ ページ)
  • index.js (ディストリビューションのプライマリ エントリ ポイント)
  • package.json (ワークフローとビルドの依存関係)
  • tsconfig.json (TypeScript コンパイラ構成)
  • webpack.config.json (Webpack 構成)

src/storage.ts

/// <reference path="../typings/index.d.ts" />
import Dexie from "dexie";

namespace storage {
  export function setupDatabase():void {
    let db = new Dexie('MyDatabase');

    db.version(1).stores({
      friends: 'name, age'
    });

    db.open().then(function () {
      console.log('Initialized database: ' + db.name);
    });
  }
}

module.exports = storage;

bower.json

{
  "name": "storage",
  "main": "dist/webpacked.js",
  "private": true,
  "dependencies": {
    "dexie": "^1.4.1"
  }
}

gulpfile.js

var gulp = require('gulp');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json');
var webpack = require('webpack-stream');

gulp.task('build', function () {
  return gulp.src('src/**/*.ts')
    .pipe(ts(tsProject))
    .pipe(gulp.dest('dist'));
});

gulp.task('webpack', function () {
  return gulp.src('dist/index.js')
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(rename('webpacked.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('default', function (done) {
  runSequence('build', 'webpack', done);
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Demo</title>
    <script src="bower_components/dexie/dist/dexie.js"></script>
    <script src="dist/webpacked.js"></script>
  </head>
  <body>
    <script>
      document.addEventListener("DOMContentLoaded", function() {
        storage.setupDatabase();
      }, false);
    </script>
  </body>
</html>

index.js

window.storage = require('./dist/storage');

パッケージ.json

{
  "name": "storage",
  "private": true,
  "devDependencies": {
    "dexie": "^1.4.1",
    "gulp": "^3.9.1",
    "gulp-rename": "^1.2.2",
    "gulp-typescript": "^2.13.6",
    "run-sequence": "^1.2.2",
    "webpack-stream": "^3.2.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}

型付け.json

{
  "globalDependencies": {
    "node": "registry:dt/node#6.0.0+20160709114037"
  }
}

注:nodeエントリは、TypeScript がステートメントでtypings install dt~node --global --save解決するために必要であり、取得されますmodulemodule.exports

webpack.config.js

module.exports = {
  externals: {
    'dexie': 'Dexie'
  }
};

アプローチ:

TypeScript コードはDexie、名前空間を使用して自身をインポートおよび宣言しますstoragecommonjs依存関係管理 ( で宣言されている)の方法に従うにはtsconfig.json、TypeScript コードでstorage名前空間をモジュールとしてエクスポートする必要がありますmodule.exports = storage

TypeScript はオブジェクトを認識しないため、そのmodule定義を取得する必要があります。このmodule定義は、 の型定義の一部であり、を使用してタイピングツールを使用して、 DefiniteTypedリポジトリnodeから取得します。ノードの取得した型定義を TypeScript でリンクするには、 を宣言する必要があります。typings install dt~node --global --save/// <reference path="../typings/index.d.ts" />

TypeScript コードを ( を使用してgulp build) コンパイルした後、エントリ ポイントを宣言して、コードにアクセスできるようにする必要があります。これは で行われindex.jsます。ビルドが成功するdist/storage.jsと、 で参照されているファイルが出力されindex.jsます。

ビルドが整ったら、コードを webpack できます (HTML5 ブラウザ用にバンドルするため)。webpack.config.js依存関係の「必要な」名前 ( dexie) をグローバル名前空間 ( ) のオブジェクトにマップしますwindow.Dexie。これにより、Dexieがコンパイル済みコードの一部ではないことが保証されます ( dist/webpacked.js)。

を取得したらwebpacked.js、ブラウザで使用できます。ただし、すべての外部依存関係が HTML ページで参照されていることを確認する必要があります (これが、Bowerを使用して Dexie がフロントエンドの依存関係としても宣言されている理由です)。

于 2016-07-19T16:28:53.210 に答える