Skip to content

const enum in a component always generates a runtime object #281

Closed
@dkzlv

Description

@dkzlv

Describe the bug
If you use a const enum in the <script> tag it will still generate a runtime object.

To Reproduce

  1. use official template and run the official script for TS support
  2. disable terser rollup plugin (to have readable output). Also, even though the default state of preserveConstEnums is false, you can set it just to be sure.
  3. replace App.svelte contents with this:
<script lang='ts'>
  const enum State {
    opened,
    closed,
  }
  let state = State.opened;
  // We add this so it is not moved into module context
  state++
</script>
  1. run npm build or just look into IDE tab with the pre-built version of the component. It will look like this:
/* generated by Svelte v3.29.7 */
import { SvelteComponent, init, safe_not_equal } from "svelte/internal";

function instance($$self) {
	var State;

	(function (State) {
		State[State["opened"] = 0] = "opened";
		State[State["closed"] = 1] = "closed";
	})(State || (State = {}));

	let state = State.opened;

	// We add this so it is not moved into module context
	state++;

	return [];
}

class Component extends SvelteComponent {
	constructor(options) {
		super();
		init(this, options, instance, null, safe_not_equal, {});
	}
}

export default Component;

Expected behavior
Should be built into something like this:

/* generated by Svelte v3.29.7 */
import { SvelteComponent, init, safe_not_equal } from "svelte/internal";

function instance($$self) {
	let state = 0;

	// We add this so it is not moved into module context
	state++;

	return [];
}

class Component extends SvelteComponent {
	constructor(options) {
		super();
		init(this, options, instance, null, safe_not_equal, {});
	}
}

export default Component;

Additional context
Copied from here.

@dummdidumm suggested that the reason is the isolatedModules setting. I tried to set it into false, no luck. Also it seems to me that if you do not export the const enum isolatedModules doesn't seem to affect it at all (based mostly on this article).

I tried to compile the following TS file with and without the isolatedModules setting:

const enum State {
  closed,
  opened,
}

let state = State.closed;

export const fn = () => {}

The result seems to be the same (and correct):

"use strict";
exports.__esModule = true;
exports.fn = void 0;
var state = 0 /* closed */;
exports.fn = function () { };

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