2

I start to learn typescript today, and there's a problem.

Here is the filetree(after compiling):

dist
    index.js
src
    data.txt
    index.ts

Here is ./src/index.ts:

import { readFileSync } from 'fs';

let data = readFileSync('./data.txt');
console.log(data);

After compiling with command "tsc", it creates ./dist/index.js, absolutely the file data.txt cannot be read correctly. How to make it the right path?

Arichy
  • 93
  • 1
  • 2
  • 7
  • You can compile the files to same folder. don't pass any "outDir": "DIRECTORY" in the compiler options. – Kiba Jul 05 '18 at 17:10
  • data.txt shouldn't be in src, its a resource as in it's only used by the compiled code, so move it to dist (because you want to distribute that file with your code) and your problem will be solved. . – Adam H Jul 05 '18 at 17:15
  • Or you create a 3rd folder like `res`, move the file there, then use `../res/data.txt` and it'll always work. –  Jul 05 '18 at 17:21
  • @ChrisG That is good advice, i just didn't want to confuse the poor guy with yet another folder. – Adam H Jul 05 '18 at 17:23
  • @ChrisG But as final production, we only take out the "dist" folder, right? A 3rd folder will be so redundant. Is there any tool that can move 'data.txt' to dist and keep the path correct just like vue-cli and webpack? – Arichy Jul 05 '18 at 17:42
  • The basic idea is to run a script that a) runs `tsc` b) copies over the files. `npm` already supports this, you just need to write a script accordingly. –  Jul 05 '18 at 18:12
  • Possible duplicate of [Angular 2 + Typescript compiler copy html and css files](https://stackoverflow.com/questions/38708200/angular-2-typescript-compiler-copy-html-and-css-files) –  Jul 05 '18 at 18:12

1 Answers1

4

Usually you are not supposed to put data in src folder. There are several ways if you really want to do so:

  1. copy data.txt to dist while compiling typescript
  2. use absolute path which could be path.join(__dirname, "../src/data.txt")
  3. Since you already know index.ts is going to be compiled to dist, use "../src/data.txt" directly
zhangjinzhou
  • 2,461
  • 5
  • 21
  • 46
  • Is there any tool that can copy 'data.txt' to dist and keep the path correct automatically while compiling just like vue-cli and webpack? – Arichy Jul 05 '18 at 18:08
  • I personally use gulp. You can include your typescript process within gulp. – zhangjinzhou Jul 05 '18 at 18:10
  • For deployment, you can simply do `tsc` and copy file on your deployment platform. For example, we use jenkins to automatically deploy node.js processes. – zhangjinzhou Jul 05 '18 at 18:14