简体   繁体   中英

Could not find a declaration file for module implicitly has an 'any' type - while importing part of CommonJS module

Currently, the project has a CommonJS module like in order to store the configuration values which are maintained only in one file:

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

This allows later to reuse them for generating JS selectors by doing:

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

The selectors are later also used in the code logic and are also passed to PostCSS config which generates a list of variables to be used in .pcss files.

This is all super handy and helps the developing flow, plus CommonJS allows to import only specific value to the components when needed like:

import { classA } from './path/classes

It worked like a dream and it still does, however, importing it the same way in the typescript file doesn't satisfy the tslint constrains and it warns with an error: Could not find a declaration file for module implicitly has an 'any' type :

Here is the 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"
  ]
}

So I wonder if there is a valid way to please TS gods and somehow declare the module types, or at least rewrite the presented logic while preserving the current functionality.

PS: After talking with a duck I came to the conclusion that rewriting it into ts module will prevent the possibility to require the selectors in the postcss config since it doesn't support ES6 import

我发现的解决方案是在tsconfig.js文件中添加"allowJs": true, option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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