首页 > 解决方案 > 打字稿:导入使用 module.exports 导出的内容

问题描述

我有以下主题文件,由于某种原因需要用 ES5 编写:

module.exports.theme = {
  primaryColor: 'blue',
  borderSize: '2px',
  // ...
}

我想将它导入 Typescript 文件(在 create-react-app 环境中)。所以我做了以下事情:

import { theme } from "../../../../session/theme";

这会导致以下错误:

Attempted import error: 'theme' is not exported from '../../../../session/theme'.

我也尝试使用module.exports.default = { ... }默认值导出和导入,但它基本上说的是同一件事(没有默认导出)。

我应该如何解决这个问题?

我的tsconfig.json样子是这样的:

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

标签: javascriptreactjstypescript

解决方案


当您的模块使用 ES5 编译时,您必须使用require而不是import。尝试这个

const theme = require('../../../../session/theme').theme;

否则需要用 ES6 编译模块


推荐阅读