Ts-node: raw file import

Created on 3 Aug 2018  路  3Comments  路  Source: TypeStrong/ts-node

It seems that ts-node doesn't support raw file import - e.g. these examples from the handbook

//ambient.d.ts
declare module "*!text" {
    const content: string;
    export default content;
}

//main.ts
import fileContent from "./xyz.txt!text";

Is it possible to support this at the transpilation level, without relying on manual/runtime file reading?

invalid

Most helpful comment

You still need the appropriate handling in node.js, see the README for more information.

I have no idea what that means.

All 3 comments

You still need the appropriate handling in node.js, see the README for more information.

You still need the appropriate handling in node.js, see the README for more information.

I have no idea what that means.

You can do this directly in nodejs, by overloading require("module")._load.

For example, with this file raw-loader.js:

const path = require('path')
const fs = require('fs')
const REQUIRE_PATH_TEST = /\.txt$/

/* eslint-disable no-underscore-dangle */

/**
 * Node will load all matched files as raw strings
 *
 * @param {RegExp} pathMatcher
 */
function register(pathMatcher = REQUIRE_PATH_TEST) {
  const Module = require('module')
  const orginalLoad = Module._load
  const cwd = process.cwd()
  Module._load = function (request, _parent) {
    if (request.match(pathMatcher)) {
      return fs.readFileSync(path.join(path.dirname(_parent ? _parent.filename : cwd), request), 'utf8')
    }
    return orginalLoad.apply(this, arguments)
  }

  return () => {
    Module._load = orginalLoad
  }
}

module.exports = {
  register,
}

You just need to do require('raw-loader.js').register(/\.txt$/) at the top of your application, before the .txt files are imported.

Depending on your tsconfig, you may need to change:

      return fs.readFileSync(path.join(path.dirname(_parent ? _parent.filename : cwd), request), 'utf8')

to

      return { default: fs.readFileSync(path.join(path.dirname(_parent ? _parent.filename : cwd), request), 'utf8') }

You can also create a file that calls the register function and just load it like that:

ts-node --require register.js index.ts
Was this page helpful?
0 / 5 - 0 ratings