Deno cotton 'must have type' - deno

I'm following a course on Deno and Angular but I am stuck. I have even downloaded the final code supplied by the person who created the course and get the same type of error.
When I try and run this commmand: deno run --allow-net --unstable app.ts
I keep getting this error message:
Check file:///?:/????/deno-admin-main/app.ts
error: Uncaught Error: Column 'role_id' must have a type!
throw new Error(Column '${propertyKey}' must have a type!);
^
at https://deno.land/x/cotton#v0.7.5/src/model.ts:76:13
at DecorateProperty (https://deno.land/x/cotton#v0.7.5/src/utils>/reflect.ts:1431:27)
at Reflect.decorate (https://deno.land/x/cotton#v0.7.5/src/utils/reflect.ts:858:16)
at __decorate (file:///?:/????/deno-admin-main/src/models/role-permission.ts:3:92)
at file:///?:/????/deno-admin-main/src/models/role-permission.ts:9:5
// role-permission
import {Model, Primary, Column} from "https://deno.land/x/cotton#v0.7.5/mod.ts";
#Model('role_permissions')
export class RolePermission {
#Primary()
id!: number;
#Column()
role_id!: number;
#Column()
permission_id!: number;
}

According to their docs the use of this cotton feature requires a custom tsconfig.json to be included when running the program:
Keep in mind that this feature requires a custom TypeScript configuration to tell Deno that we want to use TypeScript decorators (opens new window), which is currently still an experimental feature.
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
deno run --unstable --config ./tsconfig.json app.ts

The problem was a typo. I did not add "app.ts" to the file scripts.json:
{
"$schema": "https://deno.land/x/denon#2.4.7/schema.json",
"scripts": {
"start": {
"cmd": "deno run app.ts",
"desc": "run my app.ts file",
"allow": [
"net"
] ,
"tsconfig": "tsconfig.json"
}
},
"watcher": {
"match": [
"app.ts",
"src/**/*.ts"
]
}
}

Related

Uncaught ReferenceError: Buffer is not defined when executing `histoire preview` script in svelte/kit environment

I am new to SvelteKit and Vite. I love the work of Histoire ! (storybook alternative for vue and svelte)
Unfortunately I encounter an issue when trying to preview the histoire build...
Preview (histoire preview) is rendering a blank page with the following console error: Uncaught ReferenceError: Buffer is not defined coming from vendor file.
I already tried to search answers in Histoire Github existing issues section with no success. It seems like I am the only one facing this issue so I probably missing something but I don't know where. Missing config in histoire.config, svelte.config or vite.config ? Issue with deps versions ?
here some details about my environment:
// package.json
{
...
"scripts": {
...
"story:dev": "histoire dev",
"story:build": "histoire build",
"story:preview": "histoire preview"
},
"devDependencies": {
...
"#histoire/plugin-svelte": "^0.13.0",
"#sveltejs/adapter-auto": "^1.0.3",
"#sveltejs/kit": "^1.5.0",
"histoire": "^0.13.0",
"svelte": "^3.55.1",
"svelte-check": "^3.0.3",
"typescript": "^4.9.5",
"vite": "^4.1.1",
...
},
"type": "module",
...
}
I also tried to downgrade histoire to the 0.12.* without any success.
// histoire.confg.ts
import { defineConfig } from 'histoire';
import { HstSvelte } from '#histoire/plugin-svelte';
export default defineConfig({
setupFile: '/src/histoire-setup.ts',
plugins: [HstSvelte()]
});
I know that I can override the vite config of my histoire config. I tried adding an alias for Buffer and other stuff but nothing seems to work.
// svelte.config.cjs
import adapter from '#sveltejs/adapter-auto';
import { vitePreprocess } from '#sveltejs/kit/vite';
/** #type {import('#sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
export default config;
// vite.config.ts
import { sveltekit } from '#sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()],
};
export default config;
Like I said I tried multiple things to resolve this issue:
Downgrade Histoire version to 0.12.*
Override vite config of histoire.config.ts file by adding a Buffer alias and installing it as a deps
I also tried to install node-stdlib-browser following this issue answer
But nothing works as expected.

How to specify or override TypeScript config in Deno

I'm starting out on a new Deno project and ran into errors
const users = [
{ name: 'Oby', age: 12 },
{ name: 'Heera', age: 32 },
];
const loggedInUser = users.find((u) => u.name === 'Oby');
console.log(loggedInUser.age);
$ deno run hello.ts
Compile file:///Users/yangshun/Downloads/deno-test/hello.ts
error: TS2532 [ERROR]: Object is possibly 'undefined'.
console.log(loggedInUser.age);
This is caused by "strictNullChecks": true in the TypeScript config. Hence I would like to use my own tsconfig.json (TypeScript configuration) but am not sure how to go about doing so.
Create a tsconfig.json file.
{
"compilerOptions": {
"strictNullChecks": false
}
}
Execute the deno run with the -c configuration argument.
$ deno run -c tsconfig.json hello.ts
Compile file:///Users/yangshun/Downloads/deno-test/hello.ts
12

How to use TS Path Mapping with Firebase Cloud Functions

How do I use TS Path Mapping with Firebase Cloud Functions?
I tried without success:
"baseUrl": ".",
"paths": {
"#custom-path/*": ["src/utils/*"],
"#other-path/*": ["../other/path/*"]
}
Finally I was able to do this with module-alias NPM package.
Install it as non-dev dependency: yarn add module-alias #types/module-alias
Create a file fixTsPaths.ts or whatever with content like this:
import * as ModuleAlias from 'module-alias';
ModuleAlias.addAliases({
'common': __dirname + '/../../../common',
});
Here's the trick about the path /../../../common: in my case this folder is outside functions, and Typescript replicates folders structure during the build, so that's could be the reason why https://github.com/dividab/tsconfig-paths was not working out of the box. So in every case one needs to check this path and find appropriate '..' count :)
And finally import this file in your index.ts at the very top:
import './fixTsPaths';
Hope this helps!
It's 2022 and the neatest way to do this is to use tsc-alias.
On tsconfig.json, add baseUrl and add your paths under compilerOptions. Something like:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#constants/*": ["api/constants/*"],
"#interfaces/*": ["api/interfaces/*"],
"#middlewares/*": ["api/middlewares/*"],
"#modules/*": ["api/modules/*"],
"#services/*": ["api/services/*"]
},
...
}
Then, change your serve and build scripts, under package.json. Like:
...
"scripts": {
"build": "tsc && tsc-alias",
"build:watch": "concurrently \"tsc -w\" \"tsc-alias -w\"",
"serve": "concurrently --kill-others \"firebase emulators:start --only functions\" \"npm run build:watch\"",
...
},
...
☝️ here I'm using concurrently, but feel free to use whatever you like.
And that's it. You can now import stuff using your defined paths, like:
import { messages } from '#constants/responses'
import CandidatesService from '#modules/candidates/candidates.service'
import { IModule } from '#interfaces/module.interface'
etc...
The problem is the rule no-implicit-dependencies: true on the tslint.json. You can pass additional params to whitelist your custom paths:
"no-implicit-dependencies": [true, ["#custom-path", "#other-path"]],
for anyone who still struggles with this issue, but the below code at the top of the entry point file (main.ts).
don't forget to adjust the tsconfig.json file path if it is not in the default location
const tsConfig = require('../tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');
tsConfigPaths.register({
baseUrl: __dirname,
paths: tsConfig.compilerOptions.paths,
});
I was able to do this with #zerollup/ts-transform-paths NPM package.
Install #zerollup/ts-transform-paths as dev dependency: yarn add -D #zerollup/ts-transform-paths
Setup following config of webpack + ts-loader.
const tsTransformPaths = require('#zerollup/ts-transform-paths');
module.exports = {
... // other config
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => {
const transformer = tsTransformPaths(program);
return {
before: [transformer.before], // for updating paths in generated code
afterDeclarations: [transformer.afterDeclarations] // for updating paths in declaration files
};
}
}
}
]
}
};
See more in detail: https://github.com/zerkalica/zerollup/tree/5aee60287647350215c81d0b2da5a30717d9dccb/packages/ts-transform-paths

Strict Class Initialization in Typescript 2.7

So I created a sample project using the Visual Studio 2017 template 'ASP.NET Core Web Application' with Angular.
I updated the package.json created by default to the latest modules' versions.
After running the npm install command and launching the site I get and error related to TypeScript.
ERROR in [at-loader] ./ClientApp/app/components/fetchdata/fetchdata.component.ts:9:12
TS2564: Property 'forecasts' has no initializer and is not definitely assigned in the constructor.
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
client.js:67 [HMR] connected
client.js:160 [HMR] bundle has 1 errors
client.js:161 [at-loader]
./ClientApp/app/components/fetchdata/fetchdata.component.ts:9:12
TS2564: Property 'forecasts' has no initializer and is not definitely assigned in the constructor.
The error is quite clear. I researched a little bit and found out a new feature for the TS 2.7:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
Strict Class Initialization
TypeScript 2.7 introduces a new flag called --strictPropertyInitialization. This flag performs checks to ensure that each instance property of a class gets initialized in the constructor body, or by a property initializer. For example ...
This is the code where the error appears
import { Component, Inject } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'fetchdata',
templateUrl: './fetchdata.component.html'
})
export class FetchDataComponent {
public forecasts: WeatherForecast[];
constructor(http: Http, #Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
this.forecasts = result.json() as WeatherForecast[];
}, error => console.error(error));
}
}
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
And this is my tsconfig.json file
{
"compilerOptions": {
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
//"skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
"strictPropertyInitialization": false,
"strict": false,
"lib": [ "es6", "dom" ],
"types": [ "webpack-env" ]
},
"exclude": [ "bin", "node_modules" ],
"atom": { "rewriteTsconfig": false }
}
Then the VS intellisense doesn't complain but the error is still there when running.
I have also tried to define the forecasts field with public forecasts: WeatherForecast[]; but it didn't help
Node v9.9.0
TypeScript 2.7.2
Angular 5.2.9
You should define the field as being optional, as there will be a time interval between the constructor call and until you get the result of get that the field will be null. This does mean you will have to check that the field is not null where you use the field, but this is probably a good idea:
export class FetchDataComponent {
public forecasts?: WeatherForecast[];
// equivalent to:
// public forecasts: WeatherForecast[] | undefined;
doStuff(){
this.forecasts.push() // error Object is possibly 'undefined'
if(this.forecasts != null) {
this.forecasts.push(); // ok
}
this.forecasts!.push() // We tell the compiler we know better and not to complain about Object is possibly 'undefined'
}
}
Another option is to use the definite assignment assertion (!) which will tell the compiler the field will be initialized and will definitely not be null (a lie in this case). This exposes you to some runtime errors, but you will not need to check the fields on usage. I don't recommend this in this case, but it is your call:
export class FetchDataComponent {
public forecasts!: WeatherForecast[];
doStuff(){
this.forecasts.push() // ok
if(this.forecasts != null) {
this.forecasts.push(); // ok too
}
}
}

Warning: connect.static is not a function Use --force to continue

I am using YO lessapp project, "grunt-contrib-connect" helps me to start a node js server on 9000 port. Whenever I run grunt serve (start the server) the service is aborted due to the below warning.
Running "connect:livereload" (connect) task
Warning: connect.static is not a function Use --force to continue.
The exact error took place in the below function in Gruntfile.js
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
I have installed
npm install grunt-contrib-connect --save-dev,
npm install serve-static --save-dev
I came across few post, some suggest to turn off the firewall but no luck.
I know there is something to do with my machine or npm/node/connect version conflicts, because I tried to run the same app from other machine and it works fine.
System configuration :
Windows 7 Professional
Node -v4.1.2
npm -v2.14.4
connect#3.4.0
I have installed connect and serve-static based upon the post nodejs connect cannot find static, but still the same
Any help? Thanks in Advance
You have to install connect and serve-static:
npm install --save-dev grunt-contrib-connect serve-static
And then you have to import serve-static in Gruntfile.js:
module.exports = function (grunt) {
...
var serveStatic = require('serve-static');
grunt.initConfig({
...
connect: {
...
livereload: {
options: {
middleware: function(connect) {
return [
serveStatic('.tmp'),
connect().use('/bower_components', serveStatic('./bower_components')),
serveStatic(config.app)
];
}
}
}
From version 0.11.x, the new grunt-contrib-connect does not support connect.static and connect.directory.
You should install serve-static(for serve static files) and serve-index (for Serves pages that contain directory listings for a given path).
like this:
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
Use serveStatic instead connect.static
and
serveIndex instead connect.directory
grunt.initConfig({
connect: {
options: {
test: {
directory: 'somePath',
middleware: function(connect, options){
var _staticPath = path.resolve(options.directory);
return [serveStatic(_staticPath), serveIndex(_staticPath)]
}
}
}
}
})

Resources