首页 > 解决方案 > 设置 typescript 以使用 require 和 import 语法

问题描述

我在设置我的打字稿项目以与 ES 模块正常工作时遇到问题。我经历了几个现有的线程,但我还没有看到一个合适的解决方案。我感觉自己陷入了无限循环。

我正在尝试使用import语法正确导入 pdfmake,但我不断收到未知文件扩展名 .ts 的错误,或者在type: "module"package.json错误中删除后,因为它无法加载 ES 模块而不type: "module"位于.ts 文件中package.json

我不确定解决方法是什么,但我需要将"module"tpye 保留在我的package.json. 我尝试添加"esModuleInterop": truetsconfig.json但也没有用。

有没有办法建立一个打字稿项目来支持requireimport语法?

这是index.ts

import * as pdfMake from 'pdfmake/build/pdfmake.js';
import * as pdfFonts from 'pdfmake/build/vfs_fonts.js';
import * as fs from 'fs'
import * as jsdom from 'jsdom'
import htmlToPdfMake from 'html-to-pdfmake'

pdfMake.vfs = pdfFonts.pdfMake.vfs;
let { JSDOM } = jsdom;
let { window } = new JSDOM("");

这是我的tsconfig

{
    "compileOnSave": true,
    "compilerOptions": {
      "baseUrl": ".",
      "module": "commonjs",
      "esModuleInterop": true,
      "noImplicitAny": true,
      "removeComments": true,
      "sourceMap": true,
      "target": "ES5",
      "forceConsistentCasingInFileNames": true,
      "strictNullChecks": true,
      "allowUnreachableCode": false,
      "allowUnusedLabels": false,
      "noFallthroughCasesInSwitch": true,
      "noImplicitReturns": true,
      "noImplicitThis": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
  
      "typeRoots": [],
      "types": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
    },
    "exclude": ["node_modules"]
  }

标签: typescriptimportrequirepdfmake

解决方案


推荐阅读