here is my Gulp task:
var gulp = require('gulp');
var typescript = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
var tsProject = typescript.createProject('tsconfig.json');
var tsSources = [
'./typings/**/*.ts',
'server/**/*.ts'
];
module.exports = function () {
var tsResult = gulp.src(tsSources)
.pipe(sourcemaps.init())
.pipe(typescript(tsProject));
return tsResult.js
.pipe(sourcemaps.write())
.pipe(gulp.dest('server/'));
};
here is my tsconfig
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"watch": true,
"removeComments": true,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": false,
"noImplicitAny": false,
"noLib": false
},
"exclude": [
"fonts",
"images",
"img",
"libs",
"navigation",
"node_modules",
"pagehtmls",
"typings"
]
}
here is my ts file:
/// <reference path="../typings/_all.d.ts" />
'use strict';
import {Request, Response} from 'express';
var config = require('../../config/environment'),
auth = require('../../auth/auth.service');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
exports.getBooking = (req: Request, res: Response) => {
MongoClient.connect(config.mongoERP.uri, (err, db) => {
if (err) { return res.send(err); }
db.getCollection('customers').find({ email1: req.params.email }).toArray((err, customer) => {
if (err) { return res.send(err); }
return res.send(customer);
});
});
}
here is my tsd.json
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "typings",
"bundle": "typings/_all.d.ts",
"installed": {
"angularjs/angular.d.ts": {
"commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571"
},
"angular-ui-router/angular-ui-router.d.ts": {
"commit": "c50b111ded0a3a18b87b5abffea3150d6aca94da"
},
"jquery/jquery.d.ts": {
"commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571"
},
"lodash/lodash.d.ts": {
"commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571"
},
"node/node.d.ts": {
"commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571"
},
"socket.io-client/socket.io-client.d.ts": {
"commit": "2d4c4679bc2b509f27435a4f9da5e2de11258571"
},
"serve-static/serve-static.d.ts": {
"commit": "b57c33fec0be3cba8f5e9cec642db873565923d0"
},
"mime/mime.d.ts": {
"commit": "b57c33fec0be3cba8f5e9cec642db873565923d0"
},
"express/express.d.ts": {
"commit": "470954c4f427e0805a2d633636a7c6aa7170def8"
},
"es6-shim/es6-shim.d.ts": {
"commit": "dade4414712ce84e3c63393f1aae407e9e7e6af7"
},
"mongoose/mongoose.d.ts": {
"commit": "6766ed1d0faf02ede9e2edf2e66bbb2388c825ec"
}
}
}
I am using gulp cli version 3.9.0 and local 3.9.1
its gives the error error TS1128: Declaration or statement expected
for the import
If i remove './typings/**/*.ts', from gulp task and
path="../../server.d.ts" />
import {Request, Response} from 'express';
from my ts file its work fine but give diff error messages while compilation.
I have lot of ts file so i cant remove it.
You should not exclude all typings folder in your tsconfig as it contains definitions for the compiler, including the ones of express. Most likely you want to only exclude typings\browser for example.
Also I can recommend to use tsProject.src() instead of gulp.src so that structure of your projects is defined only in one place - tsconfig.
Hope this helps.
I faced the the Problem..
Just update your Gulp Typescript.
This worked for me.
Related
I am currently create a express-typescript boilerplate for myself and this is what i didnt expect because i build this boilerplate base on another boilerplate is express-typescript-starter
> Error: Cannot find module '#utils'
> Require stack:
> C:\Users\xflas\OneDrive\Documents\Personal Projects\Boilerplate\my-boilerplate\dist\app.js
> C:\Users\xflas\OneDrive\Documents\Personal Projects\Boilerplate\my-boilerplate\dist\server.js
And this is my tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"target": "es2017",
"lib": [
"es2017",
"esnext.asynciterable"
],
"typeRoots": [
"node_modules/#types"
],
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"module": "commonjs",
"pretty": true,
"sourceMap": true,
"declaration": true,
"outDir": "dist",
"allowJs": true,
"noEmit": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"importHelpers": true,
"baseUrl": "src",
"paths": {
"#/*": [
"*"
],
"#config": [
"config"
],
"#controllers": [
"controllers"
],
"#dtos": [
"models/dtos"
],
"#exceptions": [
"exceptions"
],
"#interfaces": [
"interfaces"
],
"#middlewares": [
"middlewares"
],
"#models": [
"models"
],
"#routes": [
"routes"
],
"#services": [
"services"
],
"#utils": [
"utils"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.json",
".env"
],
"exclude": [
"node_modules",
"src/http",
"src/logs",
"src/tests"
]
}
My app.ts
import express from 'express';
import hpp from 'hpp';
import helmet from 'helmet';
import morgan from 'morgan';
import cors from 'cors';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import cookieParser from 'cookie-parser';
import { IRoute } from '#interfaces';
import { logger, stream } from '#utils';
import { errorMiddleware } from '#middlewares';
import { Database } from '#models';
import config from '#config';
export default class App {
public app: express.Application;
public env: string;
public port: string | number;
constructor(routes: IRoute[]) {
this.app = express();
this.env = config.NODE_ENV || 'development';
this.port = config.SERVER.PORT || 8080;
this.connectToDatabase();
this.initializeMiddlewares();
this.initializeRoutes(routes);
this.initializeSwagger();
this.initializeErrorHandling();
}
private connectToDatabase() {
Database.sequelize.sync({ force: false });
}
public listen() {
this.app.listen(this.port, () => {
logger.info(`=================================`);
logger.info(`======= ENV: ${this.env} =======`);
logger.info(`🚀 App listening on the port ${this.port}`);
logger.info(`=================================`);
});
}
public getServer() {
return this.app;
}
private initializeMiddlewares() {
this.app.use(morgan(config.LOG_FORMAT, { stream }));
this.app.use(cors({ origin: config.ORIGIN, credentials: config.CREDENTIALS }));
this.app.use(hpp());
this.app.use(helmet());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cookieParser());
}
private initializeRoutes(routes: IRoute[]) {
routes.forEach(route => {
this.app.use('/', route.router);
});
}
private initializeSwagger() {
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Express API for Boilerplate',
version: '1.0.0',
description: 'Express Boilerplate API Docs',
},
},
apis: ['swagger.yaml'],
};
const specs = swaggerJSDoc(options);
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
}
private initializeErrorHandling() {
this.app.use(errorMiddleware);
}
}
Thank you so much
I tried to delete the node_modules and try to edit the tsconfig.json with types: ["node"] but it not working
When importing the npm Redis module into a TypeScript application, I receive the error:
node_modules/#node-redis/client/dist/lib/client/index.d.ts:45:78 - error TS1256: A rest element must be last in a tuple type.
45 export declare type ClientLegacyCommandArguments = LegacyCommandArguments | [...LegacyCommandArguments, ClientLegacyCallback];
The error is from the import statement in my redis.ts file:
import { createClient } from 'redis';
class RedisCache {
private client: any;
async init() {
const client = createClient();
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
await client.set('key', 'value');
const value = await client.get('key');
console.log(value);
}
}
const reditCache = new RedisCache();
export default reditCache;
Here is a subset of the dependencies from the package.json file:
{
"dependencies": {
"express": "4.17.1",
"passport": "0.4.1",
"passport-jwt": "^4.0.0",
"redis": "^4.0.1",
"typescript": "4.1.3"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"resolveJsonModule": true,
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
}
},
"include": [
"src/**/*",
"src/locales/*.json",
]
}
I've tried adding the types package (#types/redis) but the error still shows. This seems to be an issue with the Redis module and TypeScript. Has anyone had experience with this error before? Thanks in advance for any help.
Your code works on node14 if you remove the any type. My package.json uses:
"#tsconfig/node14": "^1.0.1",
"redis": "^4.0.4"
class RedisCache {
//private client: any;
async init() {
const client = createClient();
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
await client.set('key', 'value');
const value = await client.get('key');
console.log("In class");
console.log(value);
}
}
const reditCache = new RedisCache();
reditCache.init();
#MichaelG node-redis v4 works with TypeScript v4 and up, try to upgrade your TypeScript engine
When running
npm run electron:serve
I get this error:
in ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
I think I understand the error. My webpack doesn't know how to handle the .node file in this dependency ("msnodesqlv8": "^2.2.0")
I have tried adding node-loader but I've not had any success with it. I have tried configuring it in my vue.config.js like this:
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('node')
.test(/\.node$/)
.use('node-loader')
.loader('node-loader')
.end();
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}
I also tried adding a separate webpack.config.js with no success:
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
How can I get this working?
You need to move the node loader into the chainWebpack of the electron builder for this to work.
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
// THESE NEXT 3 LINES HERE:
chainWebpackMainProcess: config => {
config.module.rule('node').test(/\.node$/).use('node-loader').loader('node-loader').end()
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}
I have been looking through all of the other posts about the same issues in react/typescript projects but none of these have worked for me...not even changing noImplicitAny to false and strict to false is ts.config or setting the "excludes" and "typeRoots".
I've tried declaring a module, I've tried putting it in a .d.ts file, I've tried using #ts-ignore, I can't get anything to work. It's driving me crazy...can somebody tell me how to resolve this once and for all so I can get this to compile properly?
There are a whole lot more issues of the same type in the index.js file but once with a ton of requires throwing the same issue but once I can resolve this, I should be able to fix the others as well...
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['rest/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./rest/index')); **<---- ERROR HERE**
}
}(function(restIndex) {
return restIndex;
}));
EDIT:
Client.js:
var apiKey = process.env.ROCKSET_APIKEY;
var apiServer = process.env.ROCKSET_APISERVER;
var rockset = require('rockset')(apiKey, apiServer);
var getResponseLogger = function(callback) {
return function(error, response, body) {
if(error) {
console.log(error.response.error.text);
callback();
} else {
console.log(response);
callback();
}
}
}
export function getMaxSkill() {
rockset.queries.query({
'sql': {
'query': 'select * from "testCollection"'
}
}, null, getResponseLogger(done))
}
function done() {
console.log('\n\n===done===');
}
App.tsx:
import {getMaxSkill} from './client';
async componentDidMount() {
getMaxSkill();
}
tsconfig
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"typeRoots": [
"../../#types",
"../../node_modules/#types"
]
},
"include": [
"src", "tests/App.test.js"
],
"paths": {
"#material-ui/core": ["./material-ui/src"],
"#material-ui/core/*": ["./material-ui/src/*"],
"#material-ui/lab": ["./material-ui-lab/src"],
"#material-ui/lab/*": ["./material-ui-lab/src/*"],
"#material-ui/styles": ["./material-ui-styles/src"],
"#material-ui/styles/*": ["./material-ui-styles/src/*"],
"#material-ui/system": ["./material-ui-system/src"],
"#material-ui/types": ["./material-ui-types"]
}
}
I am trying to add server-side rendering to my angular 4 (4.0.3) app using the universal, already integrated to platform-server.
I used this project as an example:
https://github.com/FrozenPandaz/ng-universal-demo
and also I was following this guide:
https://www.softwarearchitekt.at/post/2017/03/07/server-side-rendering-with-angular-4.aspx
My app.server.module, which is in app/server folder:
import {AppModule} from "../app.module";
import {ServerModule} from "#angular/platform-server";
import {NgModule} from "#angular/core";
import {AppComponent} from "../app.component";
import {BrowserModule} from "#angular/platform-browser";
import {APP_BASE_HREF} from '#angular/common';
import {routing} from "../app.routes";
#NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule.withServerTransition({
appId: 'kassir'
}),
ServerModule,
AppModule,
routing
],
providers: [
{provide: APP_BASE_HREF, useValue: "/site/"}
]
}
)
export class ServerAppModule {
}
tsconfig.server.json:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"noEmit": true,
"noEmitHelpers": true,
"importHelpers": true,
"strictNullChecks": false,
"lib": [
"es2015",
"dom"
],
"typeRoots": [
"node_modules/#types"
],
"types": [
"hammerjs",
"node"
]
},
"awesomeTypescriptLoaderOptions": {
"forkChecker": true,
"useWebpackText": true
},
"angularCompilerOptions": {
"entryModule": "./app/server/app.server.module#ServerAppModule"
},
"exclude": [
"node_modules",
"dist",
"src/**/*.spec.ts",
"src/**/*.e2e.ts",
"../src/main.browser.aot.ts"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true,
"useWebpackText": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}
webpack config for server, which is merged then to the common config:
const ngtools = require('#ngtools/webpack');
const path = require('path');
const ngcWebpack = require('ngc-webpack');
const helpers = require('./helpers');
module.exports = function(env){
return {
entry:{
"main": helpers.root('./src/main.server.ts')
},
output: {
path: path.join(process.cwd(), "dist/server"),
filename: "[name].server.bundle.js",
//chunkFilename: "[id].server.chunk.js"
},
node: {
fs: 'empty'
},
plugins: [
new ngtools.AotPlugin({
"entryModule": helpers.root('/src/app/server/app.server.module.ts#ServerAppModule'),
"exclude": [],
"tsConfigPath": helpers.root("./tsconfig.server.json"),
"skipCodeGeneration": true
}),
],
target: 'node',
module: {
rules: [
{
test: /\.ts$/,
loaders: ['#ngtools/webpack', 'angular2-template-loader']
},
]
}
}
};
Everything builds ok, main.server.bundle.js gets generated but when i start it
nodemon dist/server/main.server.bundle.js
i get a clean exit even with an empty server:
import * as express from 'express';
var server = express();
server.listen(8080, function (err) {
if (err) {
console.log(err);
} else {
console.log("server started at port 8080");
}
});
It supposed to fire either success log message or error but I can't see none of them. I also tried to launch it with node command with no success.
Would appreciate any help regarding this issue.
P.S. I've seen plenty of examples with universal, all them are using aot for server-side and then import in server.ts like that:
import { AppServerModuleNgFactory } from './aot/src/app/app.server.module.ngfactory';
Is there any way to not generate it?