Jonas Sourlier
Jonas Sourlier

Reputation: 14435

How to import a self-made module in create-react-app?

I'm using create-react-app in my ReactJS app with TypeScript, and I would like to import a TypeScript/JavaScript module that I created in another project.

The module consists of a file mymodule.js, in which the code looks approximately like this:

var mymodule;
(function (mymodule) {
    var MyClass = /** @class */ (function () {
        function MyClass() {
        }
        MyClass.myMethod = function () {
            // code
        };
        return MyClass;
    }());
    mymodule.MyClass = MyClass;
})(mymodule || (mymodule = {}));

Then there is the type definition file mymodule.d.ts, which looks like this:

declare module mymodule {
    class MyClass {
        private static myMethod;
    }
}

In my create-react-app project, I placed these two files in the folder /src/vendor, and I want to use the module like this:

import { MyClass } from '../vendor/mymodule';

...

However, Visual Studio Code (i.e. the TypeScript compiler) says

File '.../vendor/mymodule.d.ts' is not a module. ts(2306)

When I run the project, the variables from the module (e.g. the class MyClass) are undefined.

This might be the reason for the error: The library is generated using module: "AMD", but create-react-app seems to enforce module: "esnext".

Edit: Here's the tsconfig.json of the create-react-app project:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "jsx": "react",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": [
    "src"
  ]
}

Upvotes: 0

Views: 1815

Answers (1)

Chris Hawkes
Chris Hawkes

Reputation: 12410

You can't import the file due to the fact that you are not exporting the module. In order for module loading to work, you should have an export at the bottom of your myModule class file.

export {
  mymodule
}

Upvotes: 2

Related Questions