This commit is contained in:
Elizabeth Craig 2024-03-14 19:54:38 -07:00
Родитель cbf0a24049
Коммит e4f03d5d54
17 изменённых файлов: 274 добавлений и 64 удалений

Просмотреть файл

@ -0,0 +1,29 @@
import { nodeExecTask, tscTask, task, parallel, watch } from 'just-scripts';
task('typescript', tscTask({}));
task('typescript:watch', tscTask({ watch: true }));
task('customNodeTask', nodeExecTask({ enableTypeScript: 'esm', args: ['./tasks/customTask.ts'] }));
task('build', parallel('customNodeTask', 'typescript'));
task('watch', parallel('typescript:watch'));
task('start', () => {
return parallel(
() =>
watch(['./src/**/*.js'], () => {
console.log('dude js');
}),
() =>
watch(['./src/**/*.ts'], () => {
console.log('dude ts');
}),
);
});
task('w', () => {
const watcher = watch(['./src/**/*.js']);
watcher.on('change', (evt, file) => {
console.log(file, 'is changed', evt);
});
});

Просмотреть файл

@ -0,0 +1,17 @@
{
"name": "example-lib-esm-ts",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "just-scripts build"
},
"license": "MIT",
"engines": {
"node": ">=14"
},
"devDependencies": {
"just-scripts": ">=2.2.3 <3.0.0",
"ts-node": "^10.0.0"
}
}

Просмотреть файл

@ -0,0 +1 @@
console.log('hello');

Просмотреть файл

@ -0,0 +1 @@
const a = 5;

Просмотреть файл

@ -0,0 +1,7 @@
import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
const dirname = path.dirname(fileURLToPath(import.meta.url));
export const packageJson = fs.readFileSync(path.resolve(dirname, '../package.json'), 'utf-8');

Просмотреть файл

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"declarationMap": true,
"outDir": "lib",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": []
},
"include": ["src"]
}

Просмотреть файл

@ -0,0 +1,29 @@
import { nodeExecTask, tscTask, task, parallel, watch } from 'just-scripts';
task('typescript', tscTask({}));
task('typescript:watch', tscTask({ watch: true }));
task('customNodeTask', nodeExecTask({ enableTypeScript: true, args: ['./tasks/customTask.js'] }));
task('build', parallel('customNodeTask', 'typescript'));
task('watch', parallel('typescript:watch'));
task('start', () => {
return parallel(
() =>
watch(['./src/**/*.js'], () => {
console.log('dude js');
}),
() =>
watch(['./src/**/*.ts'], () => {
console.log('dude ts');
}),
);
});
task('w', () => {
const watcher = watch(['./src/**/*.js']);
watcher.on('change', (evt, file) => {
console.log(file, 'is changed', evt);
});
});

Просмотреть файл

@ -0,0 +1,17 @@
{
"name": "example-lib-esm",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "just-scripts build"
},
"license": "MIT",
"engines": {
"node": ">=14"
},
"devDependencies": {
"just-scripts": ">=2.2.3 <3.0.0",
"ts-node": "^9.1.1"
}
}

Просмотреть файл

@ -0,0 +1 @@
console.log('hello');

Просмотреть файл

@ -0,0 +1 @@
const a = 5;

Просмотреть файл

@ -0,0 +1,7 @@
import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
const dirname = path.dirname(fileURLToPath(import.meta.url));
export const packageJson = fs.readFileSync(path.resolve(dirname, '../package.json'), 'utf-8');

Просмотреть файл

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"declarationMap": true,
"outDir": "lib",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": []
},
"include": ["src"]
}

Просмотреть файл

@ -2,13 +2,9 @@
"name": "example-lib",
"private": true,
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "just-scripts build"
},
"keywords": [],
"author": "",
"license": "MIT",
"engines": {
"node": ">=14"

Просмотреть файл

@ -17,9 +17,10 @@ export interface NodeExecTaskOptions {
env?: NodeJS.ProcessEnv;
/**
* Should this nodeExec task be using something like ts-node to execute the binary
* Whether this nodeExec task should use ts-node to execute the binary.
* If set to `esm`, it will use `ts-node/esm` instead of `ts-node/register`.
*/
enableTypeScript?: boolean;
enableTypeScript?: boolean | 'esm';
/**
* The tsconfig file to pass to ts-node for Typescript config
@ -40,21 +41,22 @@ export interface NodeExecTaskOptions {
export function nodeExecTask(options: NodeExecTaskOptions): TaskFunction {
return function () {
const { spawnOptions, enableTypeScript, tsconfig, transpileOnly } = options;
const args = [...(options.args || [])];
const env = { ...options.env };
const tsNodeRegister = resolveCwd('ts-node/register');
const esm = enableTypeScript === 'esm';
const tsNodeHelper = resolveCwd(esm ? 'ts-node/esm.mjs' : 'ts-node/register');
const nodeExecPath = process.execPath;
if (enableTypeScript && tsNodeRegister) {
options.args = options.args || [];
options.args.unshift(tsNodeRegister);
options.args.unshift('-r');
if (enableTypeScript && tsNodeHelper) {
args.unshift(esm ? '--loader' : '-r', tsNodeHelper);
Object.assign(env, getTsNodeEnv(tsconfig, transpileOnly));
options.env = { ...options.env, ...getTsNodeEnv(tsconfig, transpileOnly) };
logger.info('Executing [TS]: ' + [nodeExecPath, ...(options.args || [])].join(' '));
logger.info('Executing [TS]: ' + [nodeExecPath, ...args].join(' '));
} else {
logger.info('Executing: ' + [nodeExecPath, ...(options.args || [])].join(' '));
logger.info('Executing: ' + [nodeExecPath, ...args].join(' '));
}
return spawn(nodeExecPath, options.args, { stdio: 'inherit', env: options.env, ...spawnOptions });
return spawn(nodeExecPath, args, { stdio: 'inherit', env, ...spawnOptions });
};
}

Просмотреть файл

@ -4,6 +4,7 @@ import { resolve } from './resolve';
import { mark, logger } from 'just-task-logger';
import { enableTypeScript } from './enableTypeScript';
import { TaskFunction } from './interfaces';
import { readPackageJson } from 'just-scripts-utils';
export async function resolveConfigFile(args: { config?: string; defaultConfig?: string }): Promise<string | null> {
// Check for the old config paths/extensions first
@ -11,15 +12,12 @@ export async function resolveConfigFile(args: { config?: string; defaultConfig?:
args.config,
'./just.config.js',
'./just-task.js',
'./just.config.ts',
// Add .cjs and .mjs (.cts and .mts don't seem to work with ts-node)
'./just.config.cjs',
'./just.config.mjs',
...['.ts', '.cts', '.mts', '.cjs', '.mjs'].map(ext => `./just.config${ext}`),
args.defaultConfig,
].filter((p): p is string => !!p);
];
for (const entry of paths) {
const resolved = resolve(entry);
const resolved = entry && resolve(entry);
if (resolved) {
return resolved;
}
@ -39,40 +37,29 @@ export async function readConfig(): Promise<{ [key: string]: TaskFunction } | vo
process.exit(1);
}
const ext = path.extname(configFile).toLowerCase();
const packageJson = readPackageJson(process.cwd());
const packageIsESM = packageJson?.type === 'module';
if (ext === '.ts') {
enableTypeScript({ transpileOnly: true });
const ext = path.extname(configFile).toLowerCase();
const isESM = ext.startsWith('.m') || (packageIsESM && !ext.startsWith('.c'));
if (/^\.[cm]?ts$/.test(ext)) {
const tsSuccess = enableTypeScript({ transpileOnly: true, isESM, ext });
if (!tsSuccess) {
process.exit(1); // enableTypeScript will log the error
}
}
let configModule = undefined;
let importError: unknown;
try {
try {
if (ext !== '.cjs') {
// Rather than trying to infer the correct type in all cases, try import first.
configModule = await import(configFile);
}
} catch (e) {
importError = e;
}
// Fall back to require
configModule ||= require(configFile);
} catch (e) {
logger.error(`Invalid configuration file: ${configFile}`);
if (importError) {
logger.error(
`Initially got this error trying to import() the file:\n${
(importError as Error)?.stack || (importError as Error)?.message || importError
}`,
);
logger.error(
`Then tried to require() the file and got this error:\n${(e as Error).stack || (e as Error).message || e}`,
);
if (isESM) {
configModule = await import(configFile);
} else {
logger.error((e as Error).stack || (e as Error).message || e);
configModule = require(configFile);
}
} catch (e) {
logger.error(`Error loading configuration file: ${configFile}`);
logger.error((e as Error).stack || (e as Error).message || e);
process.exit(1);
}

Просмотреть файл

@ -2,8 +2,12 @@ import * as fse from 'fs-extra';
import { resolve } from './resolve';
import { logger } from 'just-task-logger';
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function enableTypeScript({ transpileOnly = true }): void {
/**
* Enable typescript support with ts-node.
* Returns true if successful.
*/
export function enableTypeScript(params: { transpileOnly?: boolean; isESM?: boolean; ext?: string }): boolean {
const { transpileOnly = true, isESM = false, ext = '' } = params;
const tsNodeModule = resolve('ts-node');
if (tsNodeModule) {
@ -16,31 +20,38 @@ export function enableTypeScript({ transpileOnly = true }): void {
supportsNode16Setting = major > 4 || (major === 4 && minor >= 7);
}
const tsNode = require(tsNodeModule);
const tsNode = require(tsNodeModule) as typeof import('ts-node');
const tsNodeMajor = Number(String(tsNode.VERSION || '0').split('.')[0]);
if (tsNodeMajor < 10) {
if (isESM) {
logger.error('ts-node >= 10 is required for ES module support.');
return false;
}
if (ext !== '.ts') {
logger.error(`ts-node >= 10 is required for ${ext} extension support.`);
return false;
}
}
tsNode.register({
transpileOnly,
skipProject: true,
compilerOptions: {
target: 'es2017',
module: supportsNode16Setting ? 'node16' : 'commonjs',
// module: supportsNode16Setting ? 'node16' : 'commonjs',
module: isESM ? 'NodeNext' : supportsNode16Setting ? 'node16' : 'commonjs',
strict: false,
skipLibCheck: true,
skipDefaultLibCheck: true,
moduleResolution: supportsNode16Setting ? 'node16' : 'node',
// moduleResolution: supportsNode16Setting ? 'node16' : 'node',
moduleResolution: isESM ? 'NodeNext' : supportsNode16Setting ? 'node16' : 'node',
allowJs: true,
esModuleInterop: true,
},
files: ['just.config.ts'],
});
} else {
logger.error(`In order to use TypeScript with just.config.ts, you need to install "ts-node" module:
npm install -D ts-node
or
yarn add -D ts-node
`);
return true;
}
logger.error(`In order to use TypeScript with just.config.ts, you need to install the "ts-node" package.`);
return false;
}

Просмотреть файл

@ -1008,6 +1008,13 @@
resolved "https://registry.yarnpkg.com/@braintree/sanitize-url/-/sanitize-url-3.1.0.tgz#8ff71d51053cd5ee4981e5a501d80a536244f7fd"
integrity sha512-GcIY79elgB+azP74j8vqkiXz8xLFfIzbQJdlwOPisgbKT00tviJQuEghOXSMVxJ00HoYJbGswr4kcllUc4xCcg==
"@cspotcode/source-map-support@^0.8.0":
version "0.8.1"
resolved "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz#00629c35a688e05a88b1cda684fb9d5e73f000a1"
integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==
dependencies:
"@jridgewell/trace-mapping" "0.3.9"
"@eslint-community/eslint-utils@^4.2.0":
version "4.4.0"
resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz#a23514e8fb9af1269d5f7788aa556798d61c6b59"
@ -1276,6 +1283,11 @@
"@jridgewell/sourcemap-codec" "^1.4.10"
"@jridgewell/trace-mapping" "^0.3.9"
"@jridgewell/resolve-uri@^3.0.3":
version "3.1.2"
resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz#7a0ee601f60f99a20c7c7c5ff0c80388c1189bd6"
integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==
"@jridgewell/resolve-uri@^3.1.0":
version "3.1.1"
resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721"
@ -1291,6 +1303,14 @@
resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32"
integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==
"@jridgewell/trace-mapping@0.3.9":
version "0.3.9"
resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9"
integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==
dependencies:
"@jridgewell/resolve-uri" "^3.0.3"
"@jridgewell/sourcemap-codec" "^1.4.10"
"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.17", "@jridgewell/trace-mapping@^0.3.18", "@jridgewell/trace-mapping@^0.3.9":
version "0.3.19"
resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz#f8a3249862f91be48d3127c3cfe992f79b4b8811"
@ -1444,6 +1464,26 @@
dependencies:
defer-to-connect "^1.0.1"
"@tsconfig/node10@^1.0.7":
version "1.0.9"
resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.9.tgz#df4907fc07a886922637b15e02d4cebc4c0021b2"
integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==
"@tsconfig/node12@^1.0.7":
version "1.0.11"
resolved "https://registry.yarnpkg.com/@tsconfig/node12/-/node12-1.0.11.tgz#ee3def1f27d9ed66dac6e46a295cffb0152e058d"
integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==
"@tsconfig/node14@^1.0.0":
version "1.0.3"
resolved "https://registry.yarnpkg.com/@tsconfig/node14/-/node14-1.0.3.tgz#e4386316284f00b98435bf40f72f75a09dabf6c1"
integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==
"@tsconfig/node16@^1.0.2":
version "1.0.4"
resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.4.tgz#0b92dcc0cc1c81f6f306a381f28e31b1a56536e9"
integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==
"@types/argparse@1.0.38":
version "1.0.38"
resolved "https://registry.yarnpkg.com/@types/argparse/-/argparse-1.0.38.tgz#a81fd8606d481f873a3800c6ebae4f1d768a56a9"
@ -2365,11 +2405,21 @@ acorn-jsx@^5.3.2:
resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"
integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==
acorn-walk@^8.1.1:
version "8.3.2"
resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.3.2.tgz#7703af9415f1b6db9315d6895503862e231d34aa"
integrity sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==
acorn@^6.4.1:
version "6.4.2"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6"
integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==
acorn@^8.4.1:
version "8.11.3"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.11.3.tgz#71e0b14e13a4ec160724b38fb7b0f233b1b81d7a"
integrity sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==
acorn@^8.9.0:
version "8.10.0"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.10.0.tgz#8be5b3907a67221a81ab23c7889c4c5526b62ec5"
@ -10984,6 +11034,25 @@ ts-jest@^29.0.5:
semver "^7.5.3"
yargs-parser "^21.0.1"
ts-node@^10.0.0:
version "10.9.2"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.2.tgz#70f021c9e185bccdca820e26dc413805c101c71f"
integrity sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==
dependencies:
"@cspotcode/source-map-support" "^0.8.0"
"@tsconfig/node10" "^1.0.7"
"@tsconfig/node12" "^1.0.7"
"@tsconfig/node14" "^1.0.0"
"@tsconfig/node16" "^1.0.2"
acorn "^8.4.1"
acorn-walk "^8.1.1"
arg "^4.1.0"
create-require "^1.1.0"
diff "^4.0.1"
make-error "^1.1.1"
v8-compile-cache-lib "^3.0.1"
yn "3.1.1"
ts-node@^9.1.1:
version "9.1.1"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-9.1.1.tgz#51a9a450a3e959401bda5f004a72d54b936d376d"
@ -11410,6 +11479,11 @@ uuid@^9.0.0:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-9.0.0.tgz#592f550650024a38ceb0c562f2f6aa435761efb5"
integrity sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==
v8-compile-cache-lib@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf"
integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==
v8-to-istanbul@^9.0.1:
version "9.1.0"
resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz#1b83ed4e397f58c85c266a570fc2558b5feb9265"