---
url: /ja/rules/no-variable-construct-id.md
---

# no-variable-construct-id

このルールは、Construct ID に変数を使用することを禁止します。

Construct ID に変数を使用することは、以下の問題を引き起こす可能性があるため適切ではありません\
(for, while, forEach, map などのループ処理と arrow function または constructor 以外の class method の中に定義されたリソースは対象外です)

* 不要な重複
* パラメータ変更時のリソース再作成
* ID の一意性を重視するあまり、不要な文字列を混在させてしまう

***

#### 🔧 使用方法

::: code-group

```ts [Oxlint]
// oxlint.config.ts
export default defineConfig({
  // ... some configs
  rules: {
    "awscdk/no-variable-construct-id": "error",
  },
});
```

```js [ESLint]
// eslint.config.mjs
export default defineConfig({
  // ... some configs
  rules: {
    "awscdk/no-variable-construct-id": "error",
  },
});
```

:::

#### ✅ 適切な例

```ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";

export interface MyConstructProps {
  environments: Record<string, string>;
}

class MyConstruct extends Construct {
  constructor(scope: Construct, id: string, props: MyConstructProps) {
    super(scope, id);

    // ✅ 文字列リテラルを指定している
    new Bucket(this, "Bucket");

    // ✅ ループ変数内では Construct ID に変数を指定可能
    for (const [key, value] of Object.entries(props.environments)) {
      new Bucket(this, `${key}Bucket`);
    }

    // ✅ Arrow function の内では Construct ID に変数を指定可能
    const myArrowFunction = (id: string) => new Bucket(this, id);
  }

  // ✅ Class method の内では Construct ID に変数を指定可能
  myClassMethod(id: string) {
    return new Bucket(this, id);
  }
}

// ✅ Construct クラス外の関数では検出されない
function createBucket(scope: Construct, id: string) {
  new Bucket(scope, id);
}
```

#### ❌ 不適切な例

```ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";

export interface MyConstructProps {
  readonly stage: string;
}

class MyConstruct extends Construct {
  constructor(scope: Construct, id: string, props: MyConstructProps) {
    super(scope, id);

    // ❌ Construct ID に constructor の id プロパティを直接指定している
    //    (Construct ID に変数を直接指定している)
    new Bucket(this, id);

    // ❌ Construct ID に変数を含むテンプレート文字列を指定している
    new Bucket(this, `${props.stage}Bucket`);
  }
}
```
