简体   繁体   English

如何在开发模式下使用 TypeScript 和 ts-node 在 NodeJS 应用程序中导入文本文件?

[英]How to import a text file in a NodeJS app with TypeScript and ts-node in dev mode?

I have a NodeJS/Express app that I'm developing using TypeScript, Nodemon and ts-node.我有一个使用 TypeScript、Nodemon 和 ts-node 开发的 NodeJS/Express 应用程序。 In this app I have a .txt file containing some (long) text.在这个应用程序中,我有一个包含一些(长)文本的.txt文件。 I'm trying to read the content of the file and just log it to the console in dev mode .我正在尝试读取文件的内容并以开发模式将其记录到控制台。

import MyText from "./something.txt";

export const runIt = () => {
    console.log(MyText);
};

I'm importing the file directly (instead of using fs ) because of a business requirement for keeping the number of deployed files to a minimum, which means that I have to bundle the code using Webpack and the text file is loaded with:我直接导入文件(而不是使用fs ),因为业务要求将部署文件的数量保持在最低限度,这意味着我必须使用 Webpack 捆绑代码,并且文本文件加载:

module.exports = {
    /*...*/
    module: {
        rules: [
            {
                test: /\.txt/,
                type: 'asset/source'
            }
        ]
    }
}

This works: running the backend.js bundle correctly "loads" the file and logs its content.这有效:运行backend.js包正确“加载”文件并记录其内容。

The problem comes in dev mode .问题出现在开发模式中。 When I start the dev server using ts-node --files./src/server.ts I get a SyntaxError: Unexpected identifier because it's trying to parse the content of the .txt file as a module (from what I can deduce...).当我使用ts-node --files./src/server.ts启动开发服务器时,我得到一个SyntaxError: Unexpected identifier因为它试图将.txt文件的内容解析为一个模块(从我可以推断出.. .)。

What additional configuration am I missing?我缺少什么额外的配置? Is there a solution for this scenario?这种情况有解决方案吗? Is there an alternative for reading text (from) files that works well even after bundling?是否有一种替代方法可以读取文本(从)文件,即使在捆绑后也能正常工作?

Here's a codesandbox that reproduces my problem.这是一个重现我的问题的代码框。

During dev you can register a module loader在开发期间,您可以注册一个模块加载器

// txt.js
/**
 * 
 * Allow import/require raw text file
 */
const fs = require('fs')
require.extensions[".txt"]= (m, fileName)=> {
  return m._compile(`module.exports=\`${fs.readFileSync(fileName)}\``, fileName);
}

launch it like this像这样启动它

node -r ts-node/register -r ./txt.js src/server.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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