Ali Salehi
Ali Salehi

Reputation: 6999

exporting enum without module flag

I have the following typescript code:

// file1.ts
export enum Status {
    Active = 1,
    NotActive = 0
}

other parts I have

// file2
import {Status} from "./file1";
...

When I compile the code I get this message:

error TS1148: Cannot compile modules unless the '--module' flag is provided. 
Consider setting the 'module' compiler option in a 'tsconfig.json' file.

My tsconfig file, just in case:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outFile": "javascript/app.js",
        "sourceMap": true,
        "target": "es5",
        "declaration": false
    },
    "files": [
        "app.ts"
    ]
}

Now I don't want to export any modules, rather I want to produce a self contained file which has all source code, so I can just include on file on the browser.

How can rewrite/reformulate the enum to avoid this compile message and produce a self contained file ?

Thanks,

Upvotes: 0

Views: 635

Answers (2)

N-ate
N-ate

Reputation: 6933

I see in your case you don't seem to have a module. If you are struggling to include an enum in a module that is declared in another file, such as a component it can be done like so:

Declare your enum: In your component after your imports and before your @Component declaration, declare your enum. Do not make your enum a const.

export enum MyEnum { DEFAULT = 'default', WORKING = 'working', COMPLETE = 'complete' }

This make your enum accessible to your component class without having a cirular reference from declaring it in your module file.

Import your enum: In your module imports, import your enum and give it an alias.

import { MyComponent, MyEnum as _myEnum } from "./my-component.component";

Re-declare your enum: In your module after your imports and before your @NgModule, export and declare your enum as a const.

export const MyEnum = _myEnum;

Now when you import your module, MyEnum will be available to reference.

If you need to access the enum from the template then give the enum a local type that is part of the component class. Inside your component class declare:

private myEnum = MyEnum;//myEnum is accessible in the template.

Upvotes: 0

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221192

Now I don't want to export any modules, rather I want to produce a self contained file which has all source code, so I can just include on file on the browser.

If this is the case, do the following:

  1. Remove the export modifier from file1.ts
  2. Remove the entire import declaration from file2.ts
  3. Add /// <reference path="file1.ts" /> to the top of file2.ts

Now app.js will be the concatenated output of file1.ts + file2.ts.

Upvotes: 1

Related Questions