找不到模块的声明文件隐式具有'any'类型-导入CommonJS模块的一部分时

问题描述 投票:0回答:1

当前,该项目有一个CommonJS模块,例如为了存储仅在一个文件中维护的配置值:

module.exports = {
  classA: `classA`,
  classB: `classB`
  classC: `classC`
}

这允许以后通过执行以下操作来重用它们以生成JS选择器:

const CLASSES = require('./classes')

const SELECTORS = Object.keys(CLASSES).reduce((obj, key) => {
  const selectorKey = key.replace(`class`, `selector`)

  obj[selectorKey] = `.${CLASSES[key]}`

  return obj
}, {})

module.exports = SELECTORS

[选择器以后也用在代码逻辑中,并且还传递给PostCSS配置,该配置生成将在.pcss文件中使用的变量列表。

这非常方便,有助于开发流程,加上CommonJS仅在需要时才将特定值导入组件,例如:

import { classA } from './path/classes

它像梦一样运作,但仍然可以实现,但是,以相同的方式将其导入打字稿文件中并不能满足tslint约束,并且会警告您错误:Could not find a declaration file for module implicitly has an 'any' type

这里是tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noImplicitThis": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

因此,我想知道是否存在一种有效的方法来取悦TS之神并以某种方式声明模块类型,或者至少在保留当前功能的同时重写所提供的逻辑。

P.S:与鸭子交谈后,我得出的结论是,将其重写为ts模块将避免在postcss配置中要求选择器的可能性,因为它不支持ES6 import

javascript typescript commonjs
1个回答
0
投票

我发现的解决方案是将"allowJs": true,选项添加到tsconfig.js文件中>

© www.soinside.com 2019 - 2024. All rights reserved.