Skip to content

在 enum 定义之前存在访问了 enum 值的代码会导致生成的代码错位,esbuild 报错。 #100

@amanofuyu

Description

@amanofuyu

Describe the bug

先说结论,因为在替换 enum 之前先行执行 replacePlugin 替换了访问了 enum 值的代码,导致代码文件长度与 scanEnums 时不一致,enum 定义的起止位置发生了变化,所以生成的代码会错位。
测试用例如下:

// src/tests/fixtures/mod.ts

export const enum TestEnum1 {
  A = 'foo',
  B = 100,
  C = 1 << 2,
}

export const values1 = [TestEnum1.A, TestEnum1.B, TestEnum1.C]

export const enum TestEnum2 {
  A = 'foo',
  B = 100,
  C = 1 << 2,
}

export const values2 = [TestEnum2.A, TestEnum2.B, TestEnum2.C]
// src/tests/fixtures/main.ts

import { values1, TestEnum1 } from './mod'
import { values2, TestEnum2 } from './mod'

console.log(TestEnum1.A, TestEnum1.B, TestEnum1.C)
console.log(values1)

console.log(TestEnum2.A, TestEnum2.B, TestEnum2.C)
console.log(values2)

生成了如下代码:

'export const TestEnum1 = {"A": "foo",\n' +
    '"B": 100,\n' +
    '"100": "B",\n' +
    '"C": 4,\n' +
    '"4": "C"}\n' +
    '\n' +
    'export const values1 = ["foo", 100, 4]\n' +
    '\n' +
    'export const enum TestEnexport const TestEnum2 = {"A": "foo",\n' +
    '"B": 100,\n' +
    '"100": "B",\n' +
    '"C": 4,\n' +
    '"4": "C"} ["foo", 100, 4]\n'

Reproduction

如上所述

System Info

与系统无关

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions