【问题标题】:How to include .xlsx and .docx files in Typescript compilation output?如何在 Typescript 编译输出中包含 .xlsx 和 .docx 文件?
【发布时间】:2019-05-20 17:56:56
【问题描述】:

我在服务器上使用带有 NodeJS 的 Typescript。

作为服务器逻辑的一部分,我需要操作 .xlsx 和 .docx 文件,但它们不包含在 Typescript 编译输出中。 .xlsx 和 .docx 文件用作创建其他文件的模板。

这就是我的项目的样子:

package.json
package-lock.json
ormconfig.json
tsconfig.json
/src
  /reports
    --other-.ts-files
    Router.ts
    Report.xlsx //File that I want to be included in the Typescript compilation output
    Report.docx //File that I want to be included in the Typescript compilation output

如何在 Typescript 编译输出中包含 .xlsx 和 .docx 文件? 我需要在 tsconfig.json 文件中添加什么?

【问题讨论】:

  • 我只希望 Typescript 编译器将它们包含在最终输出中。
  • 但是,Typescript 不能包含 json 文件吗?
  • 我不想导入文件。我只想保留文件,以便以后我可以通过使用它的路径使用库来操作它,但我不能,因为该文件不包含在 Typescript 编译输出中。

标签: typescript xlsx docx


【解决方案1】:

1) 有可能为 nodejs 添加额外的扩展,但这种方式已经被弃用了

var fs = require('fs');

require.extensions['.txt'] = function (module, filename) {
    module.exports = fs.readFileSync(filename, 'utf8');
};

var words = require("./words.txt");

2) 你可以随时使用node的file API来读取文件

const fs = require('fs')
const path = require('path')
const css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')

3) 结合 typescript 和 webpack 可以加载自定义文件类型。例如 SVG 文件在 webpack + ts 中以这种方式加载。在这种情况下,Typescript 需要额外的类型,例如(这是前端应用程序更常见的方式):

declare module "*.svg" {
  const content: any;
  export default content;
}

4) 对于阅读 XLSX 表格,第三个是一个很好的库,名为 xlsx

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2012-11-07
    • 2019-08-26
    相关资源
    最近更新 更多