rxliuli / tsx-vscode

vscode integration for esbuild-kit/tsx

Home Page:https://marketplace.visualstudio.com/items?itemName=rxliuli.tsx

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Running in context of project root

GitTom opened this issue · comments

commented

I want to execute my TS file from the project root, so the command would be

$ tsx ./src/script.ts

Is this possible with tsx-vscode?

How is this different from running from the directory where the file is located?

commented

It changes the context in which the script runs: the current directory is that of the script rather than the project/module. So relative file references in my scripts don't work.

I don't understand, is there any relationship between using __dirname and the running directory? Is there any minimal example?

commented

A script is run within an execution context which includes a current directory, that determines how relative paths get resolved. So code like this ..

import fs from 'fs';
import path from 'path';
const inputFilespec = path.join('./src', settings.filename);
const myData = fs.readFileSync( inputFilespec, 'utf8')

will be affected because the './src' gets appended to the current directory.

BTW, __dirname is not legal in ES modules. Perhaps there is some equivalent, and either way, yes, I'm sure there are ways I could change my code to no longer depend on the current directory, but I thought I would ask about it first.

A script is run within an execution context which includes a current directory, that determines how relative paths get resolved. So code like this ..

import fs from 'fs';
import path from 'path';
const inputFilespec = path.join('./src', settings.filename);
const myData = fs.readFileSync( inputFilespec, 'utf8')

will be affected because the './src' gets appended to the current directory.

BTW, __dirname is not legal in ES modules. Perhaps there is some equivalent, and either way, yes, I'm sure there are ways I could change my code to no longer depend on the current directory, but I thought I would ask about it first.

I can add a configuration to support different running directories, but it seems difficult to satisfy every scenario, and it is recommended to modify the code.

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

If you use a build tool or something like that, you can also use plugins to automatically polyfill these global variables. https://github.com/rxliuli/liuli-tools/blob/master/packages/vite-plugin-node/src/plugins/shims.ts#L4

Release 0.3.0, support tsx.cwd configuration

fileDirname: The directory of the current file
workspaceRoot: The root directory of the current workspace
packageRoot: The root directory of the current package.json
commented

Ah, that's great, thanks!