typescript 中导入JS模块的方法

289 阅读1分钟

假如我们的项目结构是这样的:

image.png

现在我们要在myPage1中导入test1下面的t1.js应该怎么操作呢? \

// t1.js:
const a = {
    i: '66666666',
    n: '77777777'
}

export default a

首先看我们的tsconfig.json文件:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "paths": {
      "@":["src"]   // 这里指定了目录
    },
    "typeRoots": ["./typings/"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

然后我们只需要根据对应的路径编写对应的.d.ts文件即可:

declare module '@/test1/t1' {  // “@”表示src目录
    let t1: any;
    export = t1;
}

最后在需要的地方根据我们的.d.ts文件导入模块即可:\

import * as React from 'react'
import t1 from '@/test1/t1' // 这里导入

export default () => {
    return (
        <div>
            {t1.i}
        </div>
    )
}