V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
wdssmq
V2EX  ›  问与答

ts 引入作为配置项的 config.js 文件时如何解决类型问题?

  •  
  •   wdssmq · Mar 15, 2023 · 1332 views
    This topic created in 1143 days ago, the information mentioned may be changed or developed.
    import config from '../config.js'
    
    src/main.ts:3:20 - error TS7016: Could not find a declaration file for module '../config.js'. 'path/config.js' implicitly has an 'any' type.
    
    Supplement 1  ·  Mar 15, 2023
    ```js
    // config.d.ts
    import type { configInterface } from './src/types'
    declare const _default: configInterface
    export default _default

    // config.js
    exports.default = {
    // ...
    }
    ```

    ↑ 这样组合好像是可以用的,也算符合我的需要,但是写成 esm 导出就不行了;

    ```js
    // config.js
    const _default = {
    // ...
    }
    export { _default as default }
    ```

    报错:

    export { _default as default }
    ^^^^^^

    SyntaxError: Unexpected token 'export'

    虽然就结果上是解决了。。
    6 replies    2023-03-15 17:05:54 +08:00
    sechi
        1
    sechi  
       Mar 15, 2023
    把 config.js 改成 config.ts 呗
    hua123s
        2
    hua123s  
       Mar 15, 2023
    写一个 config.d.ts 呗,不然就 ts-ignore
    wdssmq
        3
    wdssmq  
    OP
       Mar 15, 2023
    AI 给了条命令,姑且备忘下 - -

    tsc --allowJs --declaration --outDir ./typings config.js
    hua123s
        4
    hua123s  
       Mar 15, 2023
    @wdssmq 我不如 AI 😭😭😭
    wdssmq
        5
    wdssmq  
    OP
       Mar 15, 2023
    @hua123s 其实,我也没说 AI 的命令有用 - -

    现在变成了 config.default 才能拿到需要的对象,然后并没有定义到正确的类型。Orz
    wdssmq
        6
    wdssmq  
    OP
       Mar 15, 2023
    tsconfig 配置了 "allowJs": true, 好像可以了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2360 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 15:48 · PVG 23:48 · LAX 08:48 · JFK 11:48
    ♥ Do have faith in what you're doing.