tsc does not compile import statement - node.js

While I'm using Node.js + Typescript, tsc does not compile import statement.
My goal is compile entities and migrate with TypeORM.
Here is my code.
file structure
node
app
entities
User.ts
lib
ormconfig.json
package.json
tsconfig.json
tsconfig.json
{
"compilerOptions": {
"rootDir": "app",
"outDir": "lib",
"moduleResolution": "node",
"strict": true,
"strictNullChecks": true,
"resolveJsonModule": true,
"declaration": true,
"allowJs": false,
"target": "es2019",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es5", "es6", "es2018", "esnext.asynciterable", "es2019", "es2020.string", "es2020.symbol.wellknown"],
"skipLibCheck": true
},
"include": ["app"]
}
package.json
{
"name": "node",
"version": "1.0.0",
"type": "module",
"description": "",
"main": "index.js",
"scripts": {
"typeorm": "ts-node ./node_modules/typeorm/cli.js -d ormconfig.json",
"build": "echo 'build server...' && tsc -b .",
"server": "tsc && node lib/server.js",
"db:sync": "typeorm schema:sync",
"db:migrate:generate": "typeorm migration:generate -d migration -n",
"db:migrate:revert": "typeorm migration:revert",
"db:migration": "typeorm migration:run"
},
"license": "ISC",
"dependencies": {
"#typegoose/typegoose": "^9.9.0",
"apollo-server-core": "^3.9.0",
"apollo-server-express": "^3.9.0",
"cors": "^2.8.5",
"express": "^4.18.1",
"graphql": "^15.3.0",
"graphql-depth-limit": "^1.1.0",
"mongoose": "^6.3.8",
"morgan": "^1.10.0",
"mysql": "^2.18.1",
"ts-node": "^10.8.1",
"type-graphql": "^1.1.1",
"typeorm": "^0.2.0",
"typescript": "^4.7.3"
},
"devDependencies": {
"#types/express": "^4.17.13",
"#types/graphql-depth-limit": "^1.1.3",
"#types/morgan": "^1.9.3",
"#types/node": "^18.0.0"
}
}
ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "test",
"database": "test",
"migrationsTableName": "migrations",
"entities": ["app/entities/*.ts"],
"migrations": ["migration/*.ts"],
"cli": {
"entitiesDir": "src/entities",
"migrationsDir": "migration"
},
"autoSchemaSync": true
}
BEFORE COMPILING
node/app/entities/User.ts
import { GraphQLInt, GraphQLString } from "graphql";
import { Field, ObjectType } from "type-graphql";
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
#ObjectType({
description: 'User',
isAbstract: false // true면 DTO 확장하여 inputType으로도 사용할 수 있다.
})
export class User extends BaseEntity {
#Field(() => GraphQLInt, { description: 'user id' })
#PrimaryGeneratedColumn({ type: 'int', comment: 'user id' })
readonly userId!: number
#Field(() => GraphQLString, { description: 'user name' })
#Column('varchar', { nullable: false, comment: 'user name', length: 10 })
name!: string
#Field(() => GraphQLString, { description: 'user phone without hyphen(-)', nullable: false })
#Column('varchar', { nullable: false, comment: 'user phone without hyphen(-)', length: 174 })
phone!: string
}
And When I do "tsc -b ."
AFTER COMPILING
node/lib/entities/User.js
"use strict";
// import { GraphQLInt, GraphQLString } from "graphql";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.User = void 0;
const graphql_1 = require("graphql");
const type_graphql_1 = require("type-graphql");
const typeorm_1 = require("typeorm");
let User = class User extends typeorm_1.BaseEntity {
};
__decorate([
(0, type_graphql_1.Field)(() => graphql_1.GraphQLInt, { description: 'user id' }),
(0, typeorm_1.PrimaryGeneratedColumn)({ type: 'int', comment: 'user id' }),
__metadata("design:type", Number)
], User.prototype, "userId", void 0);
__decorate([
(0, type_graphql_1.Field)(() => graphql_1.GraphQLString, { description: 'user name' }),
(0, typeorm_1.Column)('varchar', { nullable: false, comment: 'user name', length: 10 }),
__metadata("design:type", String)
], User.prototype, "name", void 0);
__decorate([
(0, type_graphql_1.Field)(() => graphql_1.GraphQLString, { description: 'user phone without hyphen(-)', nullable: false }),
(0, typeorm_1.Column)('varchar', { nullable: false, comment: 'user phone without hyphen(-)', length: 174 }),
__metadata("design:type", String)
], User.prototype, "phone", void 0);
User = __decorate([
(0, typeorm_1.Entity)(),
(0, type_graphql_1.ObjectType)({
description: 'User',
isAbstract: false // true면 DTO 확장하여 inputType으로도 사용할 수 있다.
})
], User);
exports.User = User;
tsc automatically hide import statement so migration would not work.
How can I fix it?

Related

#badeball/cypress-cucumber-preprocessor not generating .json report

I moved from 'cypress-cucumber-preprocessor' to #badeball/cypress-cucumber-preprocessor.
And missed the json report generated on execution.
Kindly please let me know how to generated the .json report and attached screenshot for failure test.
Package.json:
"scripts": {
"test": " npx cypress run --env TAGS=\"#home\""
},
"author": "",
"license": "ISC",
"devDependencies": {
"#badeball/cypress-cucumber-preprocessor": "^15.1.0",
"cypress": "^12.3.0",
"moment": "^2.29.4",
"multiple-cucumber-html-reporter": "^3.1.0"
},
"dependencies": {
"#bahmutov/cypress-esbuild-preprocessor": "^2.1.5",
"cypress-xpath": "^2.0.1"
},
"cypress-cucumber-preprocessor": {
"stepDefinitions": "cypress/e2e/**/*.cy.js",
"commonPath": "cypress/e2e/common/**/*.cy.js",
"filterSpecs": true,
"omitFiltered": true,
"nonGlobalStepDefinitions": true,
"cucumberJson": {
"generate": true,
"outputFolder": "cypress/cucumber_report",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
}
}
cypress.config.js
const { defineConfig } = require('cypress');
const createBundler = require('#bahmutov/cypress-esbuild-preprocessor');
const addCucumberPreprocessorPlugin =
require('#badeball/cypress-cucumber-preprocessor').addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require('#badeball/cypress-cucumber-preprocessor/esbuild').createEsbuildPlugin;
module.exports = defineConfig({
defaultCommandTimeout: 5000,
numTestsKeptInMemory: 0,
viewportWidth: 1360,
viewportHeight: 768,
env: {
username: 'xxxxxxx',
password: 'xxxxxxxx'
},
e2e: {
// Integrate #bahmutov/cypress-esbuild-preprocessor plugin.
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
// This is required for the preprocessor to be able to generate JSON reports after each run, and more,
on('file:preprocessor', bundler);
await addCucumberPreprocessorPlugin(on, config);
return config;
},
specPattern: 'cypress/e2e/**/*.feature',
},
})
According to this doc, download cucumber-json-formatter and then setup your cypress-cucumber-preprocessor JSON report like this:
"cypress-cucumber-preprocessor": {
...
"json": {
"enabled": true,
"formatter": "formatter/path/here",
"output": "report/path/here"
}
}
In addition, by default, it searches your PATH if you don't provide a "formatter".
Screenshots on failure are also attached by default.

monaco web editor, language functionality don't working

I try to recreate an existing monaco+react+typescript project to my own goals. And it's not working, unfortunately. Language functionalities don't work. When I tried to throw alerts from the setupLanguage function it's working on getWorkerUrl function only. But don't work for the monaco.languages.onLanguage event processor.
May I ask you to show me the point where I'm wrong?
Regards, vladimir
P.s. Code are available on https://github.com/vladimirkozhaev/monaco-web-editor-new-edition
This is my setup.ts
import * as monaco from "monaco-editor-core";
import { languageExtensionPoint, languageID } from "./config";
import { richLanguageConfiguration, monarchLanguage } from "./TodoLang";
import { TodoLangWorker } from "./todoLangWorker";
import { WorkerManager } from "./WorkerManager";
import DiagnosticsAdapter from "./DiagnosticsAdapter";
import TodoLangFormattingProvider from "./TodoLangFormattingProvider";
export function setupLanguage() {
(window as any).MonacoEnvironment = {
getWorkerUrl: function (moduleId, label) {
if (label === languageID)
return "./todoLangWorker.js";
return './editor.worker.js';
}
}
monaco.languages.register(languageExtensionPoint);
monaco.languages.onLanguage(languageID, () => {
monaco.languages.setMonarchTokensProvider(languageID, monarchLanguage);
monaco.languages.setLanguageConfiguration(languageID, richLanguageConfiguration);
const client = new WorkerManager();
const worker: WorkerAccessor = (...uris: monaco.Uri[]): Promise<TodoLangWorker> => {
return client.getLanguageServiceWorker(...uris);
};
//Call the errors provider
new DiagnosticsAdapter(worker);
monaco.languages.registerDocumentFormattingEditProvider(languageID, new TodoLangFormattingProvider(worker));
});
}
export type WorkerAccessor = (...uris: monaco.Uri[]) => Promise<TodoLangWorker>;
This is my package.json
{
"name": "todolangeditor",
"version": "1.0.0",
"description": "TodoLang editor",
"license": "UNLICENSED",
"scripts": {
"test": "jest -c jest.config.unit.js",
"start": "webpack-dev-server",
"antlr4ts": "antlr4ts ./ExpressionsParserGrammar.g4 -visitor -o ./src/ANTLR"
},
"dependencies": {
"antlr4ts": "0.5.0-alpha.4",
"monaco-editor-core": "0.18.1",
"react": "16.8.6",
"react-dom": "16.8.6"
},
"devDependencies": {
"#types/react": "16.8.12",
"source-map-loader": "^1.0.0",
"#types/react-dom": "16.8.3",
"antlr4ts-cli": "0.5.0-alpha.4",
"css-loader": "3.3.0",
"html-webpack-plugin": "3.2.0",
"style-loader": "1.0.1",
"ts-loader": "5.3.3",
"typescript": "^4.8",
"webpack": "4.29.6",
"webpack-cli": "3.3.0",
"webpack-dev-server": "3.2.1",
"ts-jest": "^29.0.3",
"#types/jest":"29.0.3"
}
}
This is my webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { SourceMapDevToolPlugin } = require("webpack");
module.exports = {
mode: 'development',
entry: {
app: './src/index.tsx',
"editor.worker": 'monaco-editor-core/esm/vs/editor/editor.worker.js',
"todoLangWorker": './src/todo-lang/todolang.worker.ts'
},
output: {
globalObject: 'self',
filename: (chunkData) => {
switch (chunkData.chunk.name) {
case 'editor.worker':
return 'editor.worker.js';
case 'todoLangWorker':
return "todoLangWorker.js"
default:
return 'bundle.[hash].js';
}
},
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.tsx?/,
loader: 'ts-loader'
},
{
test: /\.css/,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
enforce: 'pre',
use: ['source-map-loader']
}
]
},
plugins: [
// new SourceMapDevToolPlugin({
// filename: "[file].map"
// }),
new htmlWebpackPlugin({
template: './src/index.html'
})
]
}
This is my index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {setupLanguage} from "./todo-lang/setup";
import { Editor } from './components/Editor/Editor';
import { languageID } from './todo-lang/config';
import { parseAndGetSyntaxErrors, parseAndGetASTRoot } from './language-service/Parser';
setupLanguage();
const App = () => <Editor language={languageID}></Editor>;
ReactDOM.render(<App/>, document.getElementById('container'));

Deploy Nextjs app to cpanel 500 internal server error

I have a website hosted on CPanel which was previously in React, but I needed to migrate it to NextJS for SEO requirements. Now that I want to deploy it, I struggle to make it work. I followed this video : https://www.youtube.com/watch?v=lex3qZAf_Ok&t=1136s and the official NextJS documentation : https://nextjs.org/docs/advanced-features/custom-server, but in the end, when I add the Node JS app I get a 500 Internal Server Error.
When I execute node server.js on local or through cpanel terminal, it works and shows the website at localhost:3000.
I tried with all my files like in the video, and with a standalone build, but I have the same issue.
My code architecture :
package.json :
{
"name": "newglobal",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js",
"export": "next build && next export",
"lint": "next lint",
"sitemap": "next-sitemap --config next-sitemap-config.js"
},
"dependencies": {
"#emailjs/browser": "^3.6.2",
"axios": "^0.26.1",
"bootstrap": "^5.1.3",
"moment": "^2.29.3",
"next": "12.1.5",
"react": "^17.0.2",
"react-big-calendar": "^0.40.1",
"react-dom": "^17.0.2",
"react-icons": "^4.3.1",
"react-multi-carousel": "^2.8.0",
"react-responsive-carousel": "^3.2.23",
"reactstrap": "^9.0.2",
"sass": "^1.50.0",
"sharp": "^0.30.6"
},
"devDependencies": {
"babel-plugin-styled-components": "^2.0.7",
"babel-preset-next": "^1.4.0",
"eslint": "8.13.0",
"eslint-config-next": "12.1.5",
"next-sitemap": "^2.5.28",
"styled-components": "^5.3.5"
}
}
next.config.js
/** #type {import('next').NextConfig} */
const path = require("path");
const nextConfig = {
experimental: {
outputStandalone: true,
},
images : {
domains : ["res.cloudinary.com", 'http://localhost:3000'],
loader : 'imgix',
path : ''
},
reactStrictMode: true,
sassOptions: {
includePaths: [path.join(__dirname, 'src/styles')],
prependData: `#import "variables.scss";`
},
};
module.exports = nextConfig;
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/*":["src/*"],
"#/components/*":["src/components/*"],
"#/styles/*":["src/styles/*"],
"#/context/*":["src/context/*"],
"#/image/*":["public/img/*"]
}
}
}
I use the same server.js as the official documentation, or the following after the standalone build :
process.env.NODE_ENV = "production";
process.chdir(__dirname);
const NextServer = require("next/dist/server/next-server").default;
const http = require("http");
const path = require("path");
// Make sure commands gracefully respect termination signals (e.g. from Docker)
process.on("SIGTERM", () => process.exit(0));
process.on("SIGINT", () => process.exit(0));
let handler;
const server = http.createServer(async (req, res) => {
try {
await handler(req, res);
} catch (err) {
console.error(err);
res.statusCode = 500;
res.end("internal server error");
}
});
const currentPort = parseInt(process.env.PORT, 10) || 3000;
server.listen(currentPort, (err) => {
if (err) {
console.error("Failed to start server", err);
process.exit(1);
}
const addr = server.address();
const nextServer = new NextServer({
hostname: "localhost",
port: currentPort,
dir: path.join(__dirname),
dev: false,
conf: {
env: {},
webpack: null,
webpackDevMiddleware: null,
eslint: { ignoreDuringBuilds: false },
typescript: { ignoreBuildErrors: false, tsconfigPath: "tsconfig.json" },
distDir: "./.next",
cleanDistDir: true,
assetPrefix: "",
configOrigin: "next.config.js",
useFileSystemPublicRoutes: true,
generateEtags: true,
pageExtensions: ["tsx", "ts", "jsx", "js"],
target: "server",
poweredByHeader: true,
compress: true,
analyticsId: "",
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: "",
loader: "imgix",
domains: ["res.cloudinary.com", "http://localhost:3000"],
disableStaticImages: false,
minimumCacheTTL: 60,
formats: ["image/webp"],
dangerouslyAllowSVG: false,
contentSecurityPolicy: "script-src 'none'; frame-src 'none'; sandbox;",
},
devIndicators: {
buildActivity: true,
buildActivityPosition: "bottom-right",
},
onDemandEntries: { maxInactiveAge: 15000, pagesBufferLength: 2 },
amp: { canonicalBase: "" },
basePath: "",
sassOptions: {
includePaths: [
"C:\\Users\\johnk\\OneDrive\\Documents\\Elikya Academy\\global.client\\src\\styles",
],
prependData: '#import "variables.scss";',
},
trailingSlash: false,
i18n: null,
productionBrowserSourceMaps: false,
optimizeFonts: true,
excludeDefaultMomentLocales: true,
serverRuntimeConfig: {},
publicRuntimeConfig: {},
reactStrictMode: true,
httpAgentOptions: { keepAlive: true },
outputFileTracing: true,
staticPageGenerationTimeout: 60,
swcMinify: false,
experimental: {
cpus: 11,
sharedPool: true,
plugins: false,
profiling: false,
isrFlushToDisk: true,
workerThreads: false,
pageEnv: false,
optimizeCss: false,
nextScriptWorkers: false,
scrollRestoration: false,
externalDir: false,
reactRoot: false,
disableOptimizedLoading: false,
gzipSize: true,
swcFileReading: true,
craCompat: false,
esmExternals: true,
isrMemoryCacheSize: 52428800,
serverComponents: false,
fullySpecified: false,
outputFileTracingRoot: "",
outputStandalone: true,
images: { layoutRaw: false },
trustHostHeader: false,
},
configFileName: "next.config.js",
},
});
handler = nextServer.getRequestHandler();
console.log("Listening on port", currentPort);
});
try to 'next build' first before you delopy on CPanel , if you got erorr in next build you must fix it , then try deploy agin
As a workaround because I needed to deploy the website, I removed SSR from my pages and used useEffect instead, and did a next export to deploy it easily.

unhandledRejection The "path" argument must be of type string or an instance of Buffer or URL. Received undefined - Nuxtjs

When I try to build or run nuxi dev to start my application for development this error comes up and application don't work properly.
I deleted all lock files, removed module folder and run yarn install but this is still there,
This is the exception trace info from compiler.
at readFileSync (node:fs:453:35)
at extractMeta (node_modules\nuxt-route-meta\dist\index.js:52:51)
at parseRoutes (node_modules\nuxt-route-meta\dist\index.js:149:57)
at /D:/Frontend/nuxt2/node_modules/#nuxt/kit/dist/index.mjs:477:37
at /D:/Frontend/nuxt2/node_modules/hookable/dist/index.mjs:39:70
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.getContents (/D:/Frontend/nuxt2/node_modules/nuxt3/dist/chunks/index.mjs:348:9)
at async /D:/Frontend/nuxt2/node_modules/nuxt3/dist/chunks/index.mjs:1338:22
at async Promise.all (index 16)
Here is the .env file
BASE_URL=http://localhost:8000
ECHO_PORT=
HOSTNAME=http://localhost:3000
STRIPE_KEY=x
ALGOLIA_APP_ID=y
ALGOLIA_API_KEY=z
And here is the nuxt.config.ts file content.
import getSiteMeta from './utils/getSiteMeta'
import { cloneDeep } from 'lodash'
const meta = getSiteMeta()
// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
ssr: false,
// server: {
// host: process.env.HOST || 'localhost' // default: localhost
// },
sitemap: [
{
hostname: process.env.BASE_URL || 'http://localhost:3000',
path: '/sitemap.xml',
gzip: true,
},
],
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
htmlAttrs: {
lang: 'en-GB',
},
title:
'Family Tree 365 - Start your family tree today - free! Your first tree is 100% free. Sign-up to begin your genealogy journey today!',
meta: [
...meta,
{ charset: 'utf-8' },
{ name: 'HandheldFriendly', content: 'True' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ property: 'og:site_name', content: 'Family Tree 365' },
{
hid: 'description',
name: 'description',
content:
'Our user-friendly yet powerful platform lets you create your own family tree the quick and easy way. No technical knowledge is required. Start your family tree today - free!',
},
{ property: 'og:image:width', content: '2500' },
{ property: 'og:image:height', content: '780' },
{ name: 'twitter:site', content: '#familytree365' },
{ name: 'twitter:card', content: 'summary_large_image' },
],
link: [
{ rel: 'icon', href: '/favicon.ico' },
{
hid: 'canonical',
rel: 'canonical',
href: process.env.BASE_URL,
},
],
},
// Global CSS: https://go.nuxtjs.dev/config-css
// css: ["~/assets/style/enso.scss", "animate.css/animate.compat.css"],
css: [
'animate.css/animate.compat.css',
'~/assets/css/base.css',
'~/assets/style/enso.scss',
'~/assets/css/fontawesome.min.css',
],
router: {
middleware: 'auth'
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
'~/plugins/bootEnums.js',
'~/plugins/i18n.js',
'~/plugins/pRoute.js',
'~/plugins/filters.js',
'~/plugins/numberFormat.js',
'~/plugins/shortNumber.js',
'~/plugins/toastr.js',
'~/plugins/fontawesome.js',
'~/plugins/themesSettingRegister.js',
'~/plugins/bookmarksSettingRegister.js',
'~/plugins/tutorialSettingRegister.js',
'~/plugins/notificationsRegister.js',
'~/plugins/localisationRegister.js',
'~/plugins/ioRegister.js',
'~/plugins/tasksNavbarRegister.js',
'~/plugins/usersRegister.js',
'~/plugins/Validator.js',
'~/plugins/date-fns/format.js',
'~/plugins/date-fns/formatDistance.js',
'~/plugins/vue-select.js',
'~/plugins/vuelidate.js',
'~/plugins/vue-gtag.client.js',
//'~/plugins/echo.js',
"~/plugins/vue-fb-customer-chat.js",
{src: '~/plugins/vue-stripe.js', ssr: false},
],
// Auto import components: https://go.nuxtjs.dev/config-components
// components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/eslint
// "#nuxtjs/eslint-module",
'#nuxtjs/fontawesome',
'#nuxtjs/router-extras',
'#nuxtjs/vuetify',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'nuxt-vuex-router-sync',
'nuxt-route-meta',
],
fontawesome: {
icons: {
solid: true,
brands: true,
},
},
nuxtContentAlgolia: {
appId: process.env.ALGOLIA_APP_ID,
apiKey: process.env.ALGOLIA_API_KEY,
paths: [
{
name: 'articles',
index: 'articles',
fields: ['title', 'description', 'bodyPlainText'],
},
],
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BASE_URL || 'http://localhost:3000',
proxyHeaders: false,
},
appEnv: process.env.APP_ENV || 'production',
},
env: {
STRIPE_PK: process.env.STRIPE_KEY,
baseUrl: process.env.BASE_URL ||'http://localhost:3000',
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
proxyHeaders: false,
proxy: true,
credentials: true,
},
proxy: {
'/api/': process.env.BASE_URL || 'http://localhost:8000',
'/broadcasting/': process.env.BASE_URL || 'http://localhost:8000',
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
filenames: {
app: ({ isDev }) => (isDev ? '[name].js' : '[chunkhash].js'),
chunk: ({ isDev }) => (isDev ? '[name].js' : '[chunkhash].js'),
css: ({ isDev }) => (isDev ? '[name].css' : '[contenthash].css'),
img: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]'),
font: ({ isDev }) =>
isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]',
video: ({ isDev }) =>
isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]',
},
transpile: [
'#enso-ui/strings',
'vee-validate/dist/rules',
'#enso-ui/enums',
'#sentry/browser',
'#sentry/integrations',
'#enso-ui/sentry',
'#enso-ui/route-mapper',
'd3-dag',
],
extend(config) {
const isScssRule = (rule) => rule.test.toString() === '/\\.scss$/i'
config.module.rules.forEach((rule) => {
if (isScssRule(rule)) {
const normalRule = rule.oneOf.find(
({ resourceQuery, test }) =>
resourceQuery === undefined && test === undefined
)
const lazyRule = cloneDeep(normalRule)
lazyRule.test = /\.lazy\.scss$/
const idx = lazyRule.use.findIndex(({ loader }) =>
loader.includes('vue-style-loader')
)
if (idx > -1) {
lazyRule.use.splice(idx, 1, {
loader: 'style-loader',
options: {
injectType: 'lazyStyleTag',
insert: function insertAtTop(element) {
const parent = document.querySelector('head')
parent.insertBefore(element, parent.firstChild)
},
},
})
}
rule.oneOf.push(lazyRule)
}
})
// const scssRules = config.module.rules.find('scss').oneOfs;
// const normalRule = scssRules.store.get('normal');
// const lazyRule = config.module.rules.find('scss').oneOf('scss-lazy');
// normalRule.uses.values().forEach(use => {
// if (use.name !== 'vue-style-loader') {
// lazyRule.use(use.name).merge(use.entries());
// return;
// }
// lazyRule.use('style-loader')
// .loader('style-loader')
// .options({
// injectType: 'lazyStyleTag',
// insert: function insertAtTop(element) {
// const parent = document.querySelector('head');
// parent.insertBefore(element, parent.firstChild);
// },
// });
// });
// lazyRule.test(/\.lazy\.scss$/);
// scssRules.store.delete('normal', 'scss-lazy');
// scssRules.store.set('scss-lazy', lazyRule);
// scssRules.store.set('normal', normalRule);
},
},
})
Have a look at my package.json file
{
"private": true,
"scripts": {
"dev": "nuxi dev",
"build": "nuxi build",
"start": "node .output/server/index.mjs"
},
"devDependencies": {
"#fortawesome/free-brands-svg-icons": "^6.0.0",
"#nuxtjs/fontawesome": "^1.1.2",
"#nuxtjs/vuetify": "^1.12.3",
"nuxt3": "^3.0.0-27444169.120ee4f"
},
"dependencies": {
"#enso-ui/bulma": "^5.0.7",
"#enso-ui/charts": "^4.0.0",
"#enso-ui/laravel-validation": "^2.0.6",
"#enso-ui/transitions": "^2.0.11",
"#fortawesome/fontawesome-svg-core": "^1.3.0",
"#fortawesome/free-solid-svg-icons": "^6.0.0",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/router-extras": "^1.1.1",
"#nuxtjs/style-resources": "^1.2.1",
"chart": "^0.1.2",
"chart.js": "^2.9.4",
"node-sass": "^7.0.1",
"nuxt-route-meta": "^2.3.4",
"nuxt-vuex-router-sync": "^0.0.3",
"postcss": "^8.2.15",
"resolve": "1.20.0",
"vue": "^3.2.31",
"vue-chartjs": "^3.5.1",
"vue-gtag-next": "^1.14.0",
"vue-loading-overlay": "5.0",
"vuex": "^4.0.2"
}
}

How to make Typescript transpile my Sequelize model?

After transpiling the code using the command "yarn tsc", I tried to execute my code and got the error in the image below. When I went to check the reason for the error, I saw that my Sequelize model classes are not being stacked, they are empty. I couldn't find explanations anywhere about the reason for this, nor in the Sequelize documentation. Could anyone help?
My dependencies
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#types/bcrypt": "^3.0.0",
"#types/cors": "^2.8.6",
"#types/jsonwebtoken": "^8.5.0",
"#types/moment": "^2.13.0",
"#types/nodemailer": "^6.4.0",
"#types/ws": "^7.2.4",
"axios": "^0.19.2",
"bcrypt": "^4.0.1",
"cep-promise": "^3.0.9",
"class-transformer": "^0.2.3",
"class-validator": "^0.12.2",
"cors": "^2.8.5",
"discord.js": "^12.2.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"jwt-then": "^1.0.1",
"melif": "^1.0.6",
"moment": "^2.25.3",
"mysql2": "^2.1.0",
"nodemailer": "^6.4.6",
"reflect-metadata": "^0.1.13",
"sequelize": "^5.21.5",
"sequelize-cli": "^5.5.1",
"sequelize-cli-typescript": "^3.2.0-c",
"ts-node": "^8.10.1",
"typescript": "^3.9.2"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.9.6",
"#babel/plugin-transform-runtime": "^7.9.6",
"#babel/preset-env": "^7.9.6",
"#babel/preset-typescript": "^7.9.0",
"#babel/register": "^7.9.0",
"#types/bluebird": "^3.5.30",
"#types/express": "^4.17.6",
"#types/node": "^14.0.1",
"#types/sequelize": "^4.28.9",
"#types/validator": "^12.0.1",
"#typescript-eslint/eslint-plugin": "^2.33.0",
"#typescript-eslint/parser": "^2.33.0",
"eslint": "^7.0.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "^2.0.4",
"sucrase": "^3.15.0",
"typescript": "^3.9.2"
}
My 'tsconfig.json'
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
//"esModuleInterop": true,
"resolveJsonModule": true,
"experimentalDecorators": true,
"outDir": "./dist",
"target": "es6",
//"noEmit": true,
//"allowSyntheticDefaultImports": true,
"types": [
"node"
]
},
"include": [
"src"
],
"exclude": [
"node_modules"
],
"compileOnSave": false
}
Class User.ts
import { Sequelize, Model, DataTypes, HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, BelongsToManyGetAssociationsMixin, BelongsToManyAddAssociationMixin, BelongsToManyHasAssociationMixin, BelongsToManyCountAssociationsMixin, BelongsToManyCreateAssociationMixin, HasManyRemoveAssociationMixin } from 'sequelize'
import { Route } from './Route'
import { Company } from './Company'
import { Account } from './Account'
import { DoneRoute } from './DoneRoute'
import { DoneLesson } from './DoneLesson'
import { Payment } from './Payment'
export interface UserI {
id?: number | null;
name: string;
email: string;
password: string;
introduced: boolean;
paid_access_expiration: Date;
}
export class User extends Model implements UserI {
public id?: number | null;
public name!: string;
public email!: string;
public password!: string;
public introduced!: boolean;
public paid_access_expiration!: Date;
public getRoutes!: BelongsToManyGetAssociationsMixin<Route>; // Note the null assertions!
public addRoute!: BelongsToManyAddAssociationMixin<Route, number>;
public hasRoute!: BelongsToManyHasAssociationMixin<Route, number>;
public removeRoute!: HasManyRemoveAssociationMixin<Route, number>;
public countRoutes!: BelongsToManyCountAssociationsMixin;
public createRoute!: BelongsToManyCreateAssociationMixin<Route>;
public getCompanies!: BelongsToManyGetAssociationsMixin<Company>; // Note the null assertions!
public addCompany!: BelongsToManyAddAssociationMixin<Company, number>;
public hasCompany!: BelongsToManyHasAssociationMixin<Company, number>;
public removeCompany!: HasManyRemoveAssociationMixin<Company, number>;
public countCompanies!: BelongsToManyCountAssociationsMixin;
public createCompany!: BelongsToManyCreateAssociationMixin<Company>;
public getDoneRoutes!: HasManyGetAssociationsMixin<DoneRoute>; // Note the null assertions!
public addDoneRoute!: HasManyAddAssociationMixin<DoneRoute, number>;
public hasDoneRoute!: HasManyHasAssociationMixin<DoneRoute, number>;
public removeDoneRoute!: HasManyRemoveAssociationMixin<DoneRoute, number>;
public countDoneRoutes!: HasManyCountAssociationsMixin;
public createDoneRoute!: HasManyCreateAssociationMixin<DoneRoute>;
public getDoneLessons!: HasManyGetAssociationsMixin<DoneLesson>; // Note the null assertions!
public addDoneLesson!: HasManyAddAssociationMixin<DoneLesson, number>;
public hasDoneLesson!: HasManyHasAssociationMixin<DoneLesson, number>;
public removeDoneLesson!: HasManyRemoveAssociationMixin<DoneLesson, number>;
public countDoneLessons!: HasManyCountAssociationsMixin;
public createDoneLesson!: HasManyCreateAssociationMixin<DoneLesson>;
public getAccounts!: HasManyGetAssociationsMixin<Account>; // Note the null assertions!
public addAccount!: HasManyAddAssociationMixin<Account, number>;
public hasAccount!: HasManyHasAssociationMixin<Account, number>;
public removeAccount!: HasManyRemoveAssociationMixin<Account, number>;
public countAccounts!: HasManyCountAssociationsMixin;
public createAccount!: HasManyCreateAssociationMixin<Account>;
public getPayments!: HasManyGetAssociationsMixin<Payment>; // Note the null assertions!
public addPayment!: HasManyAddAssociationMixin<Payment, number>;
public hasPayment!: HasManyHasAssociationMixin<Payment, number>;
public removePayment!: HasManyRemoveAssociationMixin<Payment, number>;
public countPayments!: HasManyCountAssociationsMixin;
public createPayment!: HasManyCreateAssociationMixin<Payment>;
public readonly routes?: Route[];
public readonly companies?: Company[];
public readonly done_routes?: DoneRoute[];
public readonly done_lessons?: DoneLesson[];
public readonly accounts?: Account[];
public readonly payments?: Payment[];
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
public static associations: {
routes: Association<User, Route>;
companies: Association<User, Company>;
done_routes: Association<User, DoneRoute>;
done_lessons: Association<User, DoneLesson>;
accounts: Association<User, Account>;
payments: Association<User, Payment>;
};
}
export function init (sequelize: Sequelize): void {
User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
introduced: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: true
},
paid_access_expiration: {
type: DataTypes.DATE,
allowNull: false
}
// Colocar Relações
},
{
tableName: 'users',
sequelize: sequelize // this bit is important
}
)
}
export function associate (sequelize: Sequelize): void {
User.belongsToMany(sequelize.models.Route, { foreignKey: 'user_id', through: 'user_routes', as: 'routes' })
User.belongsToMany(sequelize.models.Company, { foreignKey: 'user_id', through: 'user_companies', as: 'companies' })
User.hasMany(sequelize.models.DoneLesson, { foreignKey: 'user_id', as: 'done_lessons' })
User.hasMany(sequelize.models.DoneRoute, { foreignKey: 'user_id', as: 'done_routes' })
User.hasMany(sequelize.models.Account, { foreignKey: 'user_id', as: 'accounts' })
User.hasMany(sequelize.models.Payment, { foreignKey: 'user_id', as: 'payments' })
}
Class User.js after command "yarn tsc"
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.associate = exports.init = exports.User = void 0;
const sequelize_1 = require("sequelize");
class User extends sequelize_1.Model {
}
exports.User = User;
function init(sequelize) {
User.init({
id: {
type: sequelize_1.DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: sequelize_1.DataTypes.STRING,
allowNull: false
},
email: {
type: sequelize_1.DataTypes.STRING,
allowNull: false
},
password: {
type: sequelize_1.DataTypes.STRING,
allowNull: false
},
introduced: {
type: sequelize_1.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: true
},
paid_access_expiration: {
type: sequelize_1.DataTypes.DATE,
allowNull: false
}
// Colocar Relações
}, {
tableName: 'users',
sequelize: sequelize // this bit is important
});
}
exports.init = init;
function associate(sequelize) {
User.belongsToMany(sequelize.models.Route, { foreignKey: 'user_id', through: 'user_routes', as: 'routes' });
User.belongsToMany(sequelize.models.Company, { foreignKey: 'user_id', through: 'user_companies', as: 'companies' });
User.hasMany(sequelize.models.DoneLesson, { foreignKey: 'user_id', as: 'done_lessons' });
User.hasMany(sequelize.models.DoneRoute, { foreignKey: 'user_id', as: 'done_routes' });
User.hasMany(sequelize.models.Account, { foreignKey: 'user_id', as: 'accounts' });
User.hasMany(sequelize.models.Payment, { foreignKey: 'user_id', as: 'payments' });
}
exports.associate = associate;
It was quite some time ago when I think I ran into this issue - but none-the-less - posting my (vaguely) remembered solution might still be helpful.
My models are in a "models" folder - and so I excluded the #babel/plugin-proposal-class-properties babel plugin from compiling that folder.
I do not remember why there is a loose: true option set. Try with/without it and see if it changes the behavior.
There is a bug logged - https://github.com/sequelize/sequelize/issues/10579 - allegedly closed (as at January 2021) - but it doesn't really seem to be solved.
{
"env": {
"development": {
"presets": [
[
"next/babel"
]
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"exclude": "models",
"loose": true
}
]
]
},
"production": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"exclude": "models",
"loose": true
}
]
]
},
...
}

Resources