Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional default export in Typescript

I have the following JS code from a tutorial:

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./configureStore.prod');
} else {
  module.exports = require('./configureStore.dev');
}

The configureStore.*.ts files both have a default export:

export default function configureStore(initialState?: State) {
    // ...
}

I want to translate the conditional export in the former code snippet into TypeScript. If I just leave the code as is, I get a compile-time error:

error TS2306: File 'configureStore.ts' is not a module.

After some trial and error I could get the following to compile:

import {Store} from "redux";
import {State} from "../reducers";

let configureStore: (state?: State) => Store<State>;

if (process.env.NODE_ENV === "production") {
  configureStore = require("./configureStore.prod");
} else {
  configureStore = require("./configureStore.dev");
}

export default configureStore;

I tried using it like this:

import configureStore from "./store/configureStore";

const store = configureStore();

But I got this error message at runtime:

TypeError: configureStore_1.default is not a function

How can I successfully translate the original code into TypeScript?

like image 858
Botond Balázs Avatar asked Jul 22 '17 05:07

Botond Balázs


1 Answers

if (process.env.NODE_ENV === "production") {
  configureStore = require("./configureStore.prod").default;
} else {
  configureStore = require("./configureStore.dev").default;
}
like image 82
unional Avatar answered Sep 22 '22 12:09

unional