Angular2 CLI Socket.io (3rd Party Library import) - import

angular-cli: 0.0.39
node: 6.2.2
os: win32 x64
I tried to import socket.io-client into an angular2 app generated with the angular-cli but i can't get it to work.
chat.component.ts
import * as io from "socket.io-client";
#Component({
...
})
export class ChatAppComponent {
...
}
system-config.ts
/** Map relative paths to URLs. */
const map: any = {
"socket.io-client": "vendor/socket.io-client/socket.io.js"
};
/** User packages configuration. */
const packages: any = {
"socket.io-client": {"defaultExtension": "js"}
};
angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/*.js',
'es6-shim/es6-shim.js',
'reflect-metadata/*.js',
'rxjs/**/*.js',
'#angular/**/*.js',
'socket.io-client/socket.io.js'
]
});
};
package.json
{
"dependencies": {
...
"socket.io-client": "^1.4.8",
"systemjs": "0.19.26"
},
"devDependencies": {
...
"typescript": "^1.8.10",
"typings": "
}
}
typings.json
{
"ambientDevDependencies": {
"angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
"jasmine": "registry:dt/jasmine#2.2.0+20160412134438",
"selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
},
"ambientDependencies": {
"es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654",
},
"globalDependencies": {
"socket.io-client": "registry:dt/socket.io-client#1.4.4+20160317120654"
}
}
Error and stacktrace
Error: Typescript found the following errors:
C:/Users/Christian/Desktop/prototypes/chat-client/tmp/broccoli_type_script_compiler-input_base_path-5WNagLgm.tmp/0/src/app/chat.component.ts (4, 21): Cannot find module 'socket.io-client'.
at BroccoliTypeScriptCompiler._doIncrementalBuild (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\lib\broccoli\broccoli-typescript.js:115:19)
at BroccoliTypeScriptCompiler.build (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\lib\broccoli\broccoli-typescript.js:43:10)
at C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\index.js:152:21
at lib$rsvp$$internal$$tryCatch (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1048:17)
at lib$rsvp$$internal$$publish (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1019:11)
at lib$rsvp$asap$$flush (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1198:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)

1) Install socket.io-client
npm install socket.io-client --save
2) Install socket.io-client typings
npm install #types/socket.io-client --save-dev
3) Import socket.io-client in your app/code
import * as io from "socket.io-client";

Is this file present node_modules/socket.io-client/socket.io.js.
Check dts file is present in typings folder for socket-io.
Since you already specified the extension in map no need to specify it again in defaultExtension of package.
Try adding format: 'cjs' OR format: 'amd' based on library in the package -> socket.io-client

system-config.ts
/** Map relative paths to URLs. */
const map: any = {
"socket.io-client": "vendor/socket.io-client/"
};
/** User packages configuration. */
const packages: any = {
"socket.io-client": {
format: 'cjs',
defaultExtension: 'js',
main: 'socket.io.js'
}
};
angular-cli-build.js
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'socket.io*/**/*.js'
]
});
};
Working like a charm angular-cli: "1.0.0-beta.10"

This works for me:
npm install --save #types/socket.io-client

Related

OneSignal issue for Ionic 6 & Capacitor

I'm trying to set OneSignal for push notifications on devices.
I did the step by step to setup methods which are shown in the OneSignal Documentation, but no luck.
I also did the official Ionic - Capacitor - Cordova methods to setup OneSignal, with no luck again.
This is the first method I did, following Ionic official Docs:
app.module.ts
...
import { OneSignal } from '#awesome-cordova-plugins/onesingal';
#NgModule({
...
providers: [OneSignal]
});
I created a PushService where I include methods from OneSignal.
push.service.ts:
import { OneSignal } '#awesome-cordova-plugins/onesignal';
export class PushService {
constructor ( private signal: OneSignal ) {}
start (): void {
this.signal.startInit ( 'MY_ONESIGNAL_APP_ID', 'FIREBASE_ID' );
this.signal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
...
this.signal.endInit();
}
}
I call "start" method on my app.component.ts, initializing on this.platform.ready...
And when I test on my device, the answer from debug is "plugin_not_installed" OneSignal
Second method I use, following instructions from the Official OneSignal Docs "Ionic & Capacitor"
Directly I put methods on my "start" in push.service.ts, I didn't call it on app.module.ts because is a function:
import { OneSignal } from 'onesignal-cordova-plugin';
export class PushService {
constructor () {}
start (): void {
OneSignal.setAppId ( 'ONESIGNAL_APP_ID' );
...
OneSignal.setNotificationWillShowInForegroundHandler ( ( d ) => console.log ( d ) );
}
}
In this case, the error is "TypeError: Cannot read properties of undefined (reading 'setAppId')"
So, any of those methods is not working.
My system info develop is:
Ionic:
Ionic CLI : 6.18.1 (C:\Users\user\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 6.0.1
#angular-devkit/build-angular : 13.1.2
#angular-devkit/schematics : 12.2.13
#angular/cli : 13.1.2
#ionic/angular-toolkit : 5.0.3
Capacitor:
Capacitor CLI : 3.3.3
#capacitor/android : 3.3.3
#capacitor/core : 3.3.3
#capacitor/ios : not installed
Utility:
cordova-res : not installed globally
native-run : 1.5.0
System:
NodeJS : v16.13.1 (C:\Program Files\nodejs\node.exe)
npm : 8.2.0
OS : Windows 10
I think you need to install the plugin - this is what I have in package.json
"onesignal-cordova-plugin": "^3.0.1"
And import like this -
import OneSignal from 'onesignal-cordova-plugin';
And also in angular.json add this part with allowedCommonJsDependencies
{
"projects": {
"app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"allowedCommonJsDependencies": [
"onesignal-cordova-plugin"
]
}
}
}
}
}
}
The official One Signal docs need improvement but they helped me to find the path to get push notifications working with Capacitor 3 and Ionic 6 using Vue on web mobile and also on Android. This is working on my projects.
The points of attention are these:
If you'll use mobile push or native push, you have to initialize Onesignal detecting the platform.
You also have to include Onesignal service worker js files somewhere they could be located by the browser.
// Call this function when your app start
function OneSignalInit() {
OneSignal.setAppId("xxxxx-xxxxxx-xxxxxx"); //Your APP ID
OneSignal.setNotificationOpenedHandler(function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
});
OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
console.log("User accepted notifications: " + accepted);
});
}
if (getPlatforms().includes("capacitor")) {
OneSignalInit();
} else {
window.OneSignal = window.OneSignal || [];
window.OneSignal.push(function () {
// You have to include some JS files from Onesignal as the docs say to do
// Place them in a place findable by the browser when the URL is resolved
window.OneSignal.SERVICE_WORKER_PARAM = { scope: '/assets/js/onesignal/' };
window.OneSignal.SERVICE_WORKER_PATH = 'assets/js/onesignal/OneSignalSDKWorker.js'
window.OneSignal.SERVICE_WORKER_UPDATER_PATH = 'assets/js/onesignal/OneSignalSDKUpdaterWorker.js'
window.OneSignal.init({
appId: "xxxxx-xxxxx-xxxxx", //Your APP ID
safari_web_id: "web.onesignal.auto.xxxxxxxxxxx",
notifyButton: {
enable: false,
},
subdomainName: "odontoenlace",
promptOptions: {
slidedown: {
prompts: [
{
type: "push", // current types are "push" & "category"
autoPrompt: true,
text: {
/* limited to 90 characters */
actionMessage: "Nos gustaría enviarte notificaciones para que estés al tanto de eventos en tu perfil.",
/* acceptButton limited to 15 characters */
acceptButton: "Aceptar",
/* cancelButton limited to 15 characters */
cancelButton: "Cancelar"
},
delay: {
pageViews: 0,
timeDelay: 1
}
}
]
}
}
});
});
}
After all that, you can use this code to detect if Onesignal is recognized and get your Onesignal user_id also known as player_id. Again, checking if you are on web or native.
if (getPlatforms().includes("capacitor")) {
OneSignal.setAppId("xxxxx-xxxxx-xxxxxx"); // Your APP ID
OneSignal.getDeviceState((stateChanges) => {
console.log(
"OneSignal getDeviceState: " + JSON.stringify(stateChanges)
);
if (stateChanges && stateChanges.hasNotificationPermission) {
console.log("Player ID: " + stateChanges.userId);
} else {
console.log("Push notifications are disabled");
}
});
} else {
console.log("Platform is not capacitor");
is_push_supported.value =
window.OneSignal.isPushNotificationsSupported();
if (is_push_supported.value) {
if (!getPlatforms().includes("capacitor")) {
window.OneSignal.getUserId((userId) => {
console.log("Player ID: " + userId);
});
}
}
}
Finally, if you're compiling your app, Capacitor's default settings for release mode, suppress externals Onesignal libraries so check on your build.gradle file that you have disabled proguard, and minifyEnabled is set to false. The best way is to leave empty the relase object
buildTypes {
release {
}
}

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

'ckeditor' is not a known element Ionic 4

I am working on an Ionic project. I am trying to integrate the CKEditor module on my project.
<ckeditor [(ngModel)]="content" editor="Editor">
</ckeditor>
I am getting an error though:
'ckeditor' is not a known element.
So, I tried some solutions, which I have found on the internet, but unfortunately, nothing worked for me.
I tried including the CUSTOM_ELEMENTS_SCHEMA and NO_ERRORS_SCHEMA. I included the FormsModule, but no chance.
I was wondering, if you could help me, please?
Thank you in advance.
so i solved the problem. I did the following:
var textarea = document.getElementById('editor1');
const ClassicEditor = require( '#ckeditor/ckeditor5-build-classic' );
ClassicEditor.create( document.getElementById( 'editor1' ) )
.then( editor => {
console.log( editor );
} )
.catch( error => {
console.error( error );
} );
install both these packages in your angular or angular-ionic app.
npm install --save #ckeditor/ckeditor5-angular
npm install --save #ckeditor/ckeditor5-build-classic
then import in module app.module.ts, and use it in component.
import * as CKEditor from '#ckeditor/ckeditor5-build-classic';
#Component({
selector: 'app-editor',
template: '<ckeditor [editor]="editor" [data]="summary"></ckeditor>',
styleUrls: ['./edit-summary.component.scss']
})
export class EditorComponent {
summary: string = `<p>Lorem ipsum</p>`
public editor = CKEditor
constructor() {
}
}
If ckeditor is not found then read following:
i.e. you have component summary.component and it is declared in summary.module then it is necessary to import CKEditorModule in summary.module.
let say you have summary.module.ts like:
import { CKEditorModule } from '#ckeditor/ckeditor5-angular';
#NgModule({
declarations: [
SummaryComponent
],
imports: [
CommonModule,
CKEditorModule,
],
exports: [
SummaryComponent
],
})
export class SummaryModule { }
then import CKEditor in summary.component.ts
import * as CKEditor from '#ckeditor/ckeditor5-angular';
#Component({
selector: 'app-edit-summary',
template: '<ckeditor [editor]="editor" [data]="summary"></ckeditor>',
styleUrls: ['./edit-summary.component.scss']
})
export class EditSummaryComponent {
summary: string = `<p>Lorem ipsum</p>`
public editor = CKEditor
constructor() {
}
}

Karma test won't run

Please help. I am new to testing with karma. When I run "karma start karma.local.conf.js" the Chrome browser window comes up but the test doesn't run. I think my app.js and my test.js are ok and I suspect that the issue is incorrect versions of the packages I'm loading in my package.json. I know I also need to include mocha and chai:
{
"devDependencies": {
"browserify": "10.2.3",
"gulp": "3.8.11",
"gulp-browserify": "0.5.1",
"karma": "0.12.16",
"karma-chai": "0.1.0",
"karma-chrome-launcher": "0.1.4",
"karma-mocha": "0.1.4",
"http-status": "0.1.8",
"underscore": "1.5.2"
}
}
Here is my karma.local.conf.js file:
module.exports = function(config) {
config.set({
files: [
'http://code.jquery.com/jquery-1.11.3.js',
'https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js',
// For ngMockE2E
'https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-mocks.js',
'./app.js',
'./test.js'
],
frameworks: ['mocha', 'chai'],
browsers: ['Chrome'],
proxies : {
'/': 'http://localhost:3000'
}
});
};
I can also post the app.js and the test.js if need be, but I think they are ok. I think the issue is in the package.json and getting the right versions of the npm packages I need.
Here is my app.js:
var app = angular.module('myApp', ['ng']);
app.directive('userMenu', function() {
return {
controller: 'MyHttpController',
template: '<div class="user" ng-show="user">' +
' Current User: {{user.profile.username}}' +
'</div>' +
'<div ng-show="!user">' +
' <a href="/auth/facebook">' +
' Log In' +
' </a>' +
'</div>'
}
});
app.controller('MyHttpController', function($scope, $http) {
$http.get('/api/v1/me').success(function(data) {
$scope.user = data.user;
});
});
Here is my test.js:
describe('Nav Bar', function() {
var injector;
var element;
var scope;
var compiler;
var httpBackend;
beforeEach(function() {
injector = angular.injector(['myApp', 'ngMockE2E']);
intercepts = {};
injector.invoke(function($rootScope, $compile, $httpBackend) {
scope = $rootScope.$new();
compiler = $compile;
httpBackend = $httpBackend;
});
});
it('shows logged in users name', function(done) {
httpBackend.expectGET('/api/v1/me').respond({
user: { profile: { username: 'John' } }
});
element = compiler('<user-menu></user-menu>')(scope);
scope.$apply();
httpBackend.flush();
assert.notEqual(element.find('.user').css('display'), 'none');
assert.equal(element.find('.user').text().trim(), 'Current User: John');
done();
});
});
Thanks in advance,
William
Here is what I did to get my tests to run:
1. Run "npm install <package name> without a version number for each package in my package.json file
2. Run "karma init" to create a new config file. By default this command creates karma.conf.js
3. Modify karma.conf.js with the information from karma.local.conf.js
4. Run "karma start". By default this command looks for a file named karma.conf.js (I had already run "npm install -g karma-cli" so I was able to run "karma start" without specifying a path
5. Next I will run "npm ls" to see what package versions were installed and create a new version of package.json for future projects.
Another solution might be to run "npm install" and then run "ncu -u" to update all the packages to the latest versions. That might work but I haven't tested it.

MongoDB throwing error Module not found: 'module'

I have a Mongo db setup on localhost:27017 and and trying to connect to it from my app that uses Webpack via Mongoose. I have Mongoose installed as a package. Here is my code:
import mongoose from 'mongoose';
var db = mongoose.connect('mongodb://localhost:27017/music-app');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
I'm pretty sure i've followed the documentation correctly but it's throwing the following compile error:
Error in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js
Module not found: 'module' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\node_modules\require_optional\node_modules\resolve-from
There is also another error in the console:
webpackHotDevClient.js:216 Error in ./~/mongoose/~/mongodb/lib/mongo_client.js
Module not found: 'dns' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\lib
# ./~/mongoose/~/mongodb/lib/mongo_client.js 12:10-24
Anyone seen this before and know how to resolve it? Is there additional packages I might need to install in node?
This error is because you're trying to use mongodb from browser, as create-react-app is a front-end app.
You should use a back-end server and use mongodb from there.
You can check out this this full-stack repo having a nodejs server with create-react-app front-end.
https://github.com/fullstackreact/food-lookup-demo
That is because Webpack can’t statically analyze if (typeof window === 'undefined') in mongoose/lib/drivers/index.js
Here is the solution:
webpackConfig.plugins = [
...,
new webpack.DefinePlugin({
'typeof window': "\"object\""
}),
...
]
Also, if you get error messages regarding mongoose, check out below configurations.
npm install node-loader --save-dev
npm install require_optional --save-dev
npm install module --save-dev
webpack.config.js
const webpackConfig = {
name : 'client',
target : 'web',
devtool : config.compiler_devtool,
resolve : {
root : paths.client(),
extensions : ['', '.js', '.jsx', '.json', '.coffee', '.node']
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module : {}
}
// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
test : /\.(js|jsx)$/,
exclude : /node_modules\/(?!(lodash-es)\/).*/,
loader : 'babel',
query : config.compiler_babel
}, {
test : /\.json$/,
loader : 'json'
}, {
test: /\.coffee$/,
loader: 'coffee-loader',
exclude: /node_modules|lib/
}, {
test: /\.node$/,
loader: 'node-loader'
}]