TypeScript サンドボックス

TypeScript プレイグラウンドの中核を担う、TypeScript および JavaScript コードを操作するための DOM ライブラリです。 TypeScript プレイグラウンド

TypeScript サンドボックスは以下の用途に使用できます。

  • ライブラリの API を探索するための IDE のようなエクスペリエンスを構築する
  • プレイグラウンドの開発者エクスペリエンスの多くを無料で利用できる、TypeScript を使用するインタラクティブな Web ツールを構築する

例えば、横にあるサンドボックスは、 DangerJS の型定義をこのコードサンプルに一切変更を加えることなく取得しています。これは、プレイグラウンドの自動型定義取得機能がデフォルトで有効になっているためです。また、URL 内のコードや選択範囲のインデックスにも同じパラメータを探します。

クリックしてみてください この URL 実際に動作しているところを確認するには。

このライブラリは、 Monaco エディター上に構築されており、高レベル API を提供しながら、単一の sandbox オブジェクトを介してすべての低レベル API へのアクセスを提供します。

TypeScript サンドボックスのコードは、 microsoft/TypeScript-Website モノレポ内にあります。

サンドボックスをダウンロード中...

使用方法

サンドボックスは monaco-editor と同じツールを使用します。つまり、このライブラリは AMD バンドルとして提供され、 VSCode ローダー を使用して require することができます。

TypeScript Web サイトで必要とするため、ホストされているコピーを こちら

から使用できます。

はじめに

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <div id="loader">Loading...</div>
  <div id="monaco-editor-embed" style="height: 800px;" />
  <script>
    // First set up the VSCode loader in a script tag
    const getLoaderScript = document.createElement('script')
    getLoaderScript.src = 'https://typescript.dokyumento.jp/js/vs.loader.js'
    getLoaderScript.async = true
    getLoaderScript.onload = () => {
      // Now the loader is ready, tell require where it can get the version of monaco, and the sandbox
      // This version uses the latest version of the sandbox, which is used on the TypeScript website

      // For the monaco version you can use unpkg or the TypeSCript web infra CDN
      // You can see the available releases for TypeScript here:
      // https://typescript.azureedge.net/indexes/releases.json
      //
      require.config({
        paths: {
          vs: 'https://typescript.azureedge.net/cdn/4.0.5/monaco/min/vs',
          // vs: 'https://unpkg.com/@typescript-deploys/monaco-editor@4.0.5/min/vs',
          sandbox: 'https://typescript.dokyumento.jp/js/sandbox',
        },
        // This is something you need for monaco to work
        ignoreDuplicateModules: ['vs/editor/editor.main'],
      })

      // Grab a copy of monaco, TypeScript and the sandbox
      require(['vs/editor/editor.main', 'vs/language/typescript/tsWorker', 'sandbox/index'], (
        main,
        _tsWorker,
        sandboxFactory
      ) => {
        const initialCode = `import {markdown, danger} from "danger"

export default async function () {
    // Check for new @types in devDependencies
    const packageJSONDiff = await danger.git.JSONDiffForFile("package.json")
    const newDeps = packageJSONDiff.devDependencies.added
    const newTypesDeps = newDeps?.filter(d => d.includes("@types")) ?? []
    if (newTypesDeps.length){
        markdown("Added new types packages " + newTypesDeps.join(", "))
    }
}
`

        const isOK = main && window.ts && sandboxFactory
        if (isOK) {
          document.getElementById('loader').parentNode.removeChild(document.getElementById('loader'))
        } else {
          console.error('Could not get all the dependencies of sandbox set up!')
          console.error('main', !!main, 'ts', !!window.ts, 'sandbox', !!sandbox)
          return
        }

        // Create a sandbox and embed it into the div #monaco-editor-embed
        const sandboxConfig = {
          text: initialCode,
          compilerOptions: {},
          domID: 'monaco-editor-embed',
        }

        const sandbox = sandboxFactory.createTypeScriptSandbox(sandboxConfig, main, window.ts)
        sandbox.editor.focus()
      })
    }

    document.body.appendChild(getLoaderScript)
  </script>
</html>

新しいファイル index.html を作成し、このコードをそのファイルに貼り付けます。

Web ブラウザでファイル index.html を開くと、ページ上部に同じサンドボックスがロードされます。

API の例

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

// Async because it needs to go  
const js = await sandbox.getRunnableJS()
console.log(js)

ユーザーの TypeScript を JavaScript に変換する

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

const dts = await sandbox.getDTSForCode()
console.log(dts)

ユーザーのエディターの DTS を取得する

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

// A worker here is a web-worker, set up by monaco-typescript
// which does the computation in the background 
const worker = await sandbox.getWorkerProcess()
const definitions =  await client.getDefinitionAtPosition(model.uri.toString(), 6)

LSP レスポンスをリクエストする

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

// Hook in to all changes to the compiler
sandbox.setDidUpdateCompilerSettings((newOptions) => {
  console.log("Compiler settings changed: ", newOptions)
})

// Update via key value
sandbox.updateCompilerSetting("allowJs", true)
// Update via an object
sandbox.updateCompilerSettings({ jsx: 0 })
// Replace the compiler settings
sandbox.setCompilerSettings({})

いくつかの異なる API を使用してコンパイラフラグを変更する

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

const start = {
  lineNumber: 0,
  column: 0
}

const end = {
  lineNumber: 0,
  column: 4
}

const decorations = sandbox.editor.deltaDecorations([], [
  {
    range: new sandbox.monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column),
    options: { inlineClassName: 'error-highlight' },
  },
])

エディターでコードを強調表示する

const sandbox = createTypeScriptSandbox(sandboxConfig, main, ts)

// Use a script to make a JSON file like:
// { 
//   "file:///node_modules/types/keyboard/index.d.ts": "export const enterKey: string"
// }
//
// Where the keys are the paths, and the values are the source-code. The sandbox
// will use the node resolution lookup strategy by default.

const dtsFiles = {} 

Object.keys(dtsFiles).forEach(path => {
  sandbox.languageServiceDefaults.addExtraLib(dts[path], path);
});

独自のプレイグラウンドを作成する。 API は主に monaco-editor API .