Skip to content

V2: with の完全排除#11

Merged
cho45 merged 7 commits intomasterfrom
v2
Jun 8, 2025
Merged

V2: with の完全排除#11
cho45 merged 7 commits intomasterfrom
v2

Conversation

@cho45
Copy link
Owner

@cho45 cho45 commented Jun 8, 2025

背景

with は既に非推奨であり、パフォーマンス的にも大きな負の側面がある https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/with#browser_compatibility

いつなくなるかわからないものを標準動作としたくない

実装方法について

  • テンプレート内で参照される変数を with 構文で束縛するのではなく、Object.keys(data) で取得した全てのキーを new Function の引数として展開し、ローカル変数として直接参照できるように。
  • テンプレート関数生成時に new Function("__this", ...keys, body) の形で、dataの各プロパティ名を引数リストに追加。
  • テンプレート実行時には func.call(null, __this, ...keys.map(k => data[k])) のように、dataの値を順番に渡す。
  • これにより、テンプレート内で foobar のように素直に変数参照ができ、with の副作用やパフォーマンス問題を回避。
  • なお、dataのキーが不正な識別子や予約語の場合はエラーとなるため、利用側で注意が必要(EJS等と同様の制約)。
  • 既存の __this オブジェクトはエスケープや行番号管理用として引き続き利用。

これにともなう破壊的な変更

  • テンプレート関数 template(t) の1引数呼び出し(関数を返す)は廃止され、必ず template(t, data) の2引数で呼び出し、即座に変換済みの文字列を返す仕様に変更されました。
  • これにより、従来の「テンプレート関数を返して後からデータを渡す」使い方はできなくなります。
  • テンプレート内で参照できる変数は data オブジェクトのプロパティのみとなり、with による暗黙的なスコープ拡張は行われません。
  • data のキーがJavaScriptの予約語や不正な識別子の場合、テンプレート生成時にエラーとなります(従来も同様の制約がありましたが、より顕在化します)。
  • 既存のコードで1引数呼び出しや関数返却を利用している場合は、すべて template(t, data) 形式に修正が必要です。

@cho45 cho45 requested a review from Copilot June 8, 2025 13:17
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR removes the deprecated with‑statement support in template rendering and updates the API to always require two arguments—template and data—so that data keys are expanded as local variables.

  • Removed tests exercising the old one-argument API and updated them to use the two-argument form.
  • Adjusted caching in micro-template.js with a new Map-based mechanism and updated the benchmark script and package.json with new dependencies and scripts.

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
test/test.js Updated tests to match the new two-argument API and removed deprecated behavior.
package.json Added benchmark script and optionalDependencies for new benchmarking libraries.
misc/benchmark.js Replaced custom benchmark with the mitata API for performance measurement.
lib/micro-template.js Refactored the template function to remove with‑statements and use a Map for caching.
README.md Updated documentation reflecting the new API and removal of with‑statement usage.

@cho45 cho45 merged commit 8e72e86 into master Jun 8, 2025
1 check passed
@cho45 cho45 deleted the v2 branch June 8, 2025 17:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants