简体   繁体   English

如何在 create-react-app 中导入自制模块?

[英]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.我在带有 TypeScript 的 ReactJS 应用create-react-app中使用create-react-app ,并且我想导入我在另一个项目中创建的 TypeScript/JavaScript 模块。

The module consists of a file mymodule.js , in which the code looks approximately like this:该模块由一个文件mymodule.js ,其中的代码大致如下所示:

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:然后是类型定义文件mymodule.d.ts ,它看起来像这样:

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:在我的create-react-app项目中,我将这两个文件放在文件夹/src/vendor ,我想像这样使用模块:

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

...

However, Visual Studio Code (ie the TypeScript compiler) says但是,Visual Studio Code(即 TypeScript 编译器)说

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

When I run the project, the variables from the module (eg the class MyClass ) are undefined .当我运行项目时,模块中的变量(例如MyClass类)是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" .这可能是错误的原因:库是使用module: "AMD"生成的,但create-react-app似乎强制执行module: "esnext"

Edit: Here's the tsconfig.json of the create-react-app project:编辑:这是create-react-app项目的 tsconfig.json:

{
  "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"
  ]
}

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.为了使模块加载工作,您应该在 myModule 类文件的底部有一个导出。

export {
  mymodule
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM