I am following alone with the VS Code typescript config.
https://code.visualstudio.com/Docs/languages/typescript
I have setup my tsconfig.json like
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "built/local/tsc.js",
"sourceMap": true
},
"include": [
"**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
and my task runner
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p", "."],
"showOutput": "always",
"problemMatcher": "$tsc"
}
My ts codes
class StartUp {
public static main(): number {
console.log('Helle Workd');
return 5;
}
}
console.log('test');
StartUp.main();
For some reason, I don't see any output in the output window when I press cmd + shift + B (build). I do see errors like
hello.ts(8,1): error TS2304: Cannot find name 'ddd'.
if I add randomly add ddd string in the codes.
Can someone help me to solve this issue? Thanks so much!
The command "tsc -p ." doesn't output any if no error in compiling and all compiled JavaScript/SourceMap files are generated, so you cannot see any in the output window of VSCode. Just type and run the command in the console.
You can add option "--diagnostics" to make the command output some information.
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p", ".", "--diagnostics"],
"problemMatcher": "$tsc"
}
The output:
Files: 2
Lines: 18225
Nodes: 73338
Identifiers: 24828
Symbols: 18969
Types: 4609
Memory used: 62579K
I/O read: 0.00s
I/O write: 0.01s
Parse time: 0.24s
Bind time: 0.12s
Check time: 0.54s
Emit time: 0.06s
Total time: 0.96s
Also see all options in http://www.typescriptlang.org/docs/handbook/compiler-options.html
Setup app structure
Setup basic html
npm init --yes
npm install lite-server --save-dev
npm install --save-dev typescript #types/node #types/jasmine #types/core-js
add script lite to scrips in package.json
create an app folder
add app.js
create tsconfig.json
add the following options
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"lib": ["es2015", "dom"]
}
}
add the following to the package.json file
{
"name": "Angular2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts":
{
"start": "concurrently \"npm run tsc:w\" \"npm run lite\"",
"lite": "lite-server",
"tsc": "tsc",
"tsc:w": "tsc -w"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies":
{
"#types/core-js": "^0.9.43",
"#types/jasmine": "^2.8.2",
"#types/node": "^8.0.53",
"concurrently": "^3.5.1",
"lite-server": "^2.3.0",
"typescript": "^2.6.1"
},
"dependencies":
{
"types": "^0.1.1"
}
}
Related
I have the following folder structure in my TypeScript project:
- azure_functions
- function_app
- functions
- project_1
function.json
index.ts
package.json
package-lock.json
tsconfig.json
node_modules
This is the current configuration of my tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "./dist",
"rootDir": "./",
"allowJs": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["./**/*.ts"],
"exclude": ["node_modules", "dist"]
}
This is the configuration of my package.json file:
{
"name": "ts_project",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "npm run build && func start",
"build": "tsc",
"watch": "tsc -w",
"prestart": "npm run build && func extensions install",
"start:host": "func start",
"test": "echo \"No tests yet...\""
},
"dependencies": {
"node-fetch": "^2.6.7"
},
"devDependencies": {
"#azure/functions": "^3.5.0",
"#types/node-fetch": "2.6.2",
"typescript": "^4.4.4"
}
}
Whenever I run npm start I see that no conversion from TS to JS is performed and I end up with an error indicating that Invalid script file name configuration. The scriptFile property is set to a file it doesn't exist.
If I do a tsc index.ts inside of the project_1 folder, I will see my file converted to js. Why am I unable to perform the same through the package.json file?
What am I missing in my tsconfig.json file?
For reference, this is the content of my function.json:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
],
"scriptFile": "../dist/functions/project_1/index.js"
}
Here I also faced the same error when I changed the scriptFile in the function.json they way you have written.
Assuming that the entire function is in the functions folder. They you should not specify the functions name in the scriptFile .
The scriptFile should be in this format
"../dist/project_1/index.js"
Now you can run the npm start in the functions folder and it should start the function
I've got a discordJS (v14) bot that I'm starting (using typescript), and when I try to build it I get the following error:
node_modules/#sapphire/shapeshift/dist/index.d.ts:590:44 - error TS2344: Type 'T' does not satisfy the constraint 'object'.
590 declare type SchemaOf<T> = ObjectValidator<T>;
~
node_modules/#sapphire/shapeshift/dist/index.d.ts:590:23
590 declare type SchemaOf<T> = ObjectValidator<T>;
~
This type parameter might need an `extends object` constraint.
node_modules/#sapphire/shapeshift/dist/index.d.ts:641:65 - error TS2344: Type 'T' does not satisfy the constraint 'object'.
641 object<T>(shape: MappedObjectValidator<T>): ObjectValidator<T, UndefinedToOptional<T>>;
~
node_modules/#sapphire/shapeshift/dist/index.d.ts:641:12
641 object<T>(shape: MappedObjectValidator<T>): ObjectValidator<T, UndefinedToOptional<T>>;
~
This type parameter might need an `extends object` constraint.
Found 2 errors in the same file, starting at: node_modules/#sapphire/shapeshift/dist/index.d.ts:590
My index.ts looks like this (yes its basic, but trying to figure out this error)
import "dotenv/config";
import "reflect-metadata";
import { Client, GatewayIntentBits } from 'discord.js';
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
]
});
client.login(process.env["DISCORD_TOKEN"]);
My package.json is:
{
"name": "my-discord-bot",
"version": "1.0.0",
"description": "My Discord Bot",
"main": "index.js",
"author": "myself",
"license": "MIT",
"private": true,
"type": "module",
"scripts": {
"cleanup": "rm -f -r ./dist/",
"build": "yarn cleanup && tsc",
"watch": "yarn cleanup && tsc -w",
"serve": "node ./dist/index.js",
"register": "node ./dist/register-commands.js",
"lint": "eslint . -ext .js,.jsx,.ts,.tsx",
"format": "prettier --write \"./src/**/*.ts\"",
"test": ""
},
"dependencies": {
"#sentry/integrations": "^7.13.0",
"#sentry/node": "^7.13.0",
"#sentry/tracing": "^7.13.0",
"anti-phish-advanced": "^1.1.0",
"axios": "^0.27.2",
"chrono-node": "^2.4.1",
"date-fns": "^2.29.3",
"discord.js": "^14.3.0",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"fuse.js": "^6.6.2",
"mysql2": "^2.3.3",
"reflect-metadata": "^0.1.13",
"steamid": "^2.0.0"
}
}
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["types/*"]
},
"outDir": "./dist/",
"module": "es2020",
"target": "es2020",
// "lib": ["es2020"],
"moduleResolution": "node",
"noImplicitAny": false,
"allowJs": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"types": ["node", "reflect-metadata"],
"typeRoots": ["node_modules/#types"]
},
"include": ["./src/**/*"],
"exclude": ["**/node_modules", "**/__tests__/*", "**/tests/"]
}
A yarn why on the erroring package
yarn why v1.22.19
[1/4] Why do we have the module "#sapphire/shapeshift"...?
[2/4] Initialising dependency graph...
[3/4] Finding dependency...
[4/4] Calculating file sizes...
=> Found "#sapphire/shapeshift#3.5.1"
info Reasons this module exists
- "discord.js##discordjs#builders" depends on it
- Hoisted from "discord.js##discordjs#builders##sapphire#shapeshift"
Does anyone know if there is anything that I'm doing that might be causing the issue? and how I might fix it? (short of just not using typescript)
https://github.com/sapphiredev/shapeshift/issues/193
Need to force resolution of the package to a higher version.
Using yarn (as I am) is easy, just add to package.json
resolutions: {
"#sapphire/shapeshift": "^3.6.0"
}
I am trying to setup a simple typescript, node environment with absolute paths instead of relative paths.
I followed the video here: but can't get the absolute imports to resolve properly when I run npm run start:dev. The VSCode intellisense is able to resolve the absolute import paths fine, but when I compile, I get compilation error.
Note: relative paths are compiling and working fine. But absolute paths are giving compilation error.
Here's my .nvmrc:
v16.15.1
Here is my code structure:
Here's my simple code:
src/index.ts:
import add from '#src/math/add';
console.log(add(2, 1));
Here #src/math/add is giving compilation error. ./math/add compiles fine.
src/math/add.ts:
import force from '#src/science/physics';
const add = (a: number, b: number): number => {
console.log(`force:${force(5, 3)}`);
return a + b;
};
export default add;
Here #src/science/physics is giving compilation error. ../science/physics compiles fine.
src/physics/force.ts:
const force = (mass: number, accelaration: number): number => mass * accelaration;
export default force;
Here is my tsconfig.json
{
"ts-node": {
"require": ["tsconfig-paths/register"],
"esm": true,
"experimentalSpecifierResolution": "node"
},
"exclude": ["node_modules", "dist", "coverage"],
"include": ["src"],
"compilerOptions": {
"target": "ES2020",
"lib": ["DOM", "ESNext"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
/* JavaScript Support */
"allowJs": true,
/* Emit */
"outDir": "dist",
"removeComments": true,
/* Type Checking */
"strict": true,
"noImplicitAny": true,
/* Modules */
"module": "ES2020",
"moduleResolution": "node",
"rootDir": "." /*meaning wherever is this tsconfig.json file, that is the root directory*/,
"baseUrl": ".",
"paths": {
"#src/*": ["src/*"]
},
/* Interop Constraints */
"isolatedModules": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
/* Completeness */
"skipLibCheck": true
}
}
Here is my package.json:
{
"type": "module",
"name": "express-proj-setup-tut",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"start:dev": "ts-node -r tsconfig-paths/register ./src/index.ts",
"start:prod": "node -r ts-node/register/transpile-only -r tsconfig-paths/register ./dist/src/index.ts",
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/node": "^18.7.9",
"#typescript-eslint/eslint-plugin": "^5.33.1",
"#typescript-eslint/parser": "^5.33.1",
"eslint": "^8.22.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.2.1",
"prettier": "^2.7.1",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.1.0",
"typescript": "^4.7.4"
}
}
Finally, here's the error message in terminal:
I would greatly appreciate if someone can help me out getting the absolute paths working.
thanks
I was unable to solve your issue with your configuration of module in package.json and module in tsconfig.json but if you remove "type": "module" from package.json and change to "module": "CommonJS" in your tsconfig.json you will be able to run "start:dev": "ts-node -r tsconfig-paths/register src/index.ts".
For me output was
force:15
3
Related question: Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
Check if your node.js version is higher than 14.6.0
Having ./src folder with ts code, ./dist folder as tsc output folder write following to map ./src as #root global path:
// tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#root/*": [
"./*"
]
}
}
}
// package.json
{
...
"imports": {
"#root/*": "./dist/*"
},
}
Such aliases should start with # symbol.
Useful links:
https://nodejs.org/api/packages.html#subpath-imports
https://www.typescriptlang.org/tsconfig#paths
In your tsconfig.json, you need change
"paths": {
"#src/*": ["src/*"]
},
for this:
"paths": {
"#/*": [
"src/*"
]
},
And in include, you need add all paths that include ts files, like this:
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
I hope that solve that compilation error :-)
package.json
{
"version": "1.0.0",
"description": "",
"dependencies": {
"#types/express": "^4.17.13",
"#types/node": "^18.6.4",
"chalk": "^5.0.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"nodemon": "^2.0.19",
"tsc-watch": "^5.0.3",
"typescript": "^4.7.4"
},
"devDependencies": {},
"scripts": {
"start": " nodemon node --es-module-specifier-resolution=node --experimental-modules dist/index.js",
"build": " tsc --watch && npm run start",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"moduleResolution": "node",
"importHelpers": true,
"target": "ESNext",
"module": "ES6",
"lib": [
"ES6",
"dom","ESNext"
],
"allowSyntheticDefaultImports": true,
"noUnusedParameters": false
},
"exclude": ["node_modules", "**/node_modules/*"],
}
my ts code
import chalk from "chalk";
import express from "express"
import { getTodo } from './addTodo';
const app = express()
app.listen(4000,()=>{
console.log(chalk.green("server is up on http://localhost:4000"))
},)
app.get("/",getTodo)
so when I compile like that its givin module not found err but when I change
import { getTodo } from './addTodo.js';
like that code every time I need to change to file extension with my hand.
I search on google to fix but they have many result have but never can fix my problem
can you help me thanks from now.
i find solution problem was
package.json
"start": " nodemon node --es-module-specifier-resolution=node --experimental-modules dist/index.js"
nodemon already starting node prompt.
so we need to delete node
"start": " nodemon --es-module-specifier-resolution=node --experimental-modules dist/index.js"
In my project I get the following from yarn test
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/danwt/Documents/work/interchain-security/diff-model-ts/node_modules/time-span/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import convertHrtime from 'convert-hrtime';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import * as fs from 'fs';
> 2 | import timeSpan from 'time-span';
...
I have viewed many pages to try to find solutions and fix this without success.
My project is nodejs using typescript and jest.
//jest.config.js
export default {
testEnvironment: 'node',
preset: 'ts-jest/presets/default-esm',
globals: {
'ts-jest': {
useESM: true,
},
},
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.(m)?js$': '$1',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(m)?ts$',
coverageDirectory: 'coverage',
collectCoverageFrom: [
'src/**/*.ts',
'src/**/*.mts',
'!src/**/*.d.ts',
'!src/**/*.d.mts',
],
};
//package.json
{
"name": "node-typescript-boilerplate",
"version": "0.0.0",
"description": "Minimalistic boilerplate to quick-start Node.js development in TypeScript.",
"type": "module",
"engines": {
"node": ">= 16.13 <17"
},
"devDependencies": {
"#types/jest": "^28.1.4",
"#types/node": "~16",
"#typescript-eslint/eslint-plugin": "~5.26",
"#typescript-eslint/parser": "~5.26",
"eslint": "~8.16",
"eslint-config-prettier": "~8.5",
"eslint-plugin-jest": "~26.2",
"jest": "^28.1.1",
"prettier": "~2.6",
"rimraf": "~3.0",
"source-map-support": "^0.5.21",
"ts-jest": "^28.0.5",
"tsutils": "~3.21",
"typescript": "~4.7"
},
"scripts": {
"start": "node build/src/main.js",
"gen": "node build/src/gen.js",
"clean": "rimraf coverage build tmp",
"prebuild": "npm run lint",
"build": "tsc -p tsconfig.json",
"build:watch": "tsc -w -p tsconfig.json",
"build:release": "npm run clean && tsc -p tsconfig.release.json",
"lint": "eslint . --ext .ts --ext .mts",
"test": "jest --coverage",
"prettier": "prettier --config .prettierrc --write .",
"test:watch": "jest --watch"
},
"author": "Jakub Synowiec <jsynowiec#users.noreply.github.com>",
"license": "Apache-2.0",
"dependencies": {
"#types/clone-deep": "^4.0.1",
"#types/underscore": "^1.11.4",
"clone-deep": "^4.0.1",
"time-span": "^5.1.0",
"tslib": "~2.4",
"underscore": "^1.13.4"
},
"volta": {
"node": "16.13.0"
}
}
//tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "node16",
"lib": [
"ES2022"
],
"moduleResolution": "Node16",
"rootDir": ".",
"outDir": "build",
"allowSyntheticDefaultImports": true,
"importHelpers": true,
"alwaysStrict": true,
"sourceMap": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": false,
"noUnusedParameters": true,
"noImplicitAny": false,
"noImplicitThis": false,
"strictNullChecks": false,
"allowJs": true
},
"include": [
"src/**/*",
"__tests__/**/*"
]
}
Here is the problematic file
//node_modules/covert-hrtime/index.d.ts
export interface HighResolutionTime {
seconds: number;
milliseconds: number;
nanoseconds: bigint;
}
export default function convertHrtime(hrtime: bigint): HighResolutionTime;
I have tried a lot of things including using transformIgnorePatterns and transform to match the problematic package in jest.config.js.
Can anybody spot the problem?
Thank you