Angular 2 not loading component - javascript

I am trying out Angular2 and I started with an example here
I can run npm install and npm start without errors, but the Component is not loaded. The selector points to my-app but the content in the tag is never replaced. I end up seeing 'Loading...' in the browser.
All code is directly copied from the sample using copy paste. I have not edited anything at all. I wonder if the sample simply does not work or if this could be something caused by my development environment?
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
typings.json
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
package.json
{
"name": "angular2-demo",
"version": "1.0.0",
"scripts": {
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.7",
"systemjs": "0.19.22",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.5.15"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.1.0",
"typescript": "^1.7.5",
"typings":"^0.6.8"
}
}
environment_app.component.ts
import {Component, View} from "angular2/core";
#Component({
selector: 'my-app'
})
#View({
template: '<h2>My First Angular 2 App</h2>'
})
export class AppComponent {
}
environment_main.ts
import {bootstrap} from "angular2/platform/browser"
import {AppComponent} from "./environment_app.component"
bootstrap(AppComponent);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}},
map: { 'app': './angular2/src/app' }
});
System.import('app/environment_main')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

A suggestion
If you are looking for starting up in Angular try and use angular cli to build your project .
Angular cli link - https://cli.angular.io/
create project using
ng new my-project
cd my-project
ng serve
you can also check my repo if you wish to hosted on gh-pages
Link - https://rahulrsingh09.github.io/AngularConcepts/

Related

Configure imports relative to root directory in create-react-library library

I am trying to setup a react component library with create-react-library (which uses rollup under the hood) and port over our application's existing component library so that we can share it between applications. I am able to create the library, publish to a private git registry, and consume it in other applications. The issue is that I have had to change all of my imports to relative imports which is rather annoying as I am planning on porting over a large amount of components, hocs and utils.
The entry point of the package is the src dir. Say I have a component in src/components/Text.js and a hoc in src/hoc/auth.js. If I want to import withAuthentication from src/hoc/auth.js into my Text component, I have to import it like import { withAuthentication } from "../hoc/auth" but I'd like to be able to import with the same paths I have in my existing application so it's easy to port over components, like import { withAuthentication } from "hoc/auth"
I have tried a lot of config options, jsconfig.json the same as my create-react-app application, manually building my library with rollup rather then using create-react-library so I'd have more config options but to no avail.
Below are the relevant bits from my package.json as well as my jsconfig.json, any help would be greatly appreciated, I am sure I am not the only person who's had this issue.
Here's the package.json
{
"main": "dist/index.js",
"module": "dist/index.modern.js",
"source": "src/index.js",
"files": [
"dist"
],
"engines": {
"node": ">=10"
},
"scripts": {
"build": "microbundle-crl --no-compress --format modern,cjs",
"start": "microbundle-crl watch --no-compress --format modern,cjs",
"prepare": "run-s build",
"test": "run-s test:unit test:lint test:build",
"test:build": "run-s build",
"test:lint": "eslint .",
"test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
"test:watch": "react-scripts test --env=jsdom",
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
},
"peerDependencies": {
"react": "^16.0.0",
"react-html-parser": "^2.0.2",
"lodash": "^4.17.19",
"#material-ui/core": "^4.11.0",
"react-redux": "^7.1.1",
"redux": "^4.0.1",
"redux-localstorage": "^0.4.1",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"react-router-dom": "^5.1.1",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1",
"react-svg": "^12.0.0",
"reselect": "^4.0.0"
},
"devDependencies": {
"microbundle-crl": "^0.13.10",
"babel-eslint": "^10.0.3",
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-config-standard-react": "^9.2.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.17.0",
"eslint-plugin-standard": "^4.0.1",
"gh-pages": "^2.2.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.4"
},
"dependencies": {
"node-sass": "^7.0.0"
}
}
and here's the jsconfig:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
The example from the following link maybe you should navigate to your src file from the BaseUrl, or if you "src" is in the same directory as your config it should be only "."
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
Example from link above:
{
"compilerOptions": {
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
}
}
}
You need to do 3 things
tsconfig.json this enables typescript autocomplete
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
"src": ["./src"]
}
}
}
babel.config.js this plugin resolves relative modules
module.exports = {
plugins: [
[
'module-resolver',
{
alias: {
src: './src'
}
}
]
]
}
package.json // install babel-plugin-module-resolver
{
//...
"devDependencies": {
//...
"babel-plugin-module-resolver": "^3.2.0",
// ...
}
}

Electron - Typescript - Cannot find module

Trying to build my electron app with typescript generated from the electron-quick-start-typescript project. I have added an additional module called auth.ts which is not recognised when I start the app. I am trying to reference it in renderer.ts with
import { myfunction } from './auth'
However I can see that it is getting converted into js. What could be causing this issue? Why can't my application see my new module?
Additionally here is my package.json file if that helps.
{
"name": "electron-quick-start-typescript",
"version": "1.0.0",
"description": "A minimal Electron application written with Typescript",
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"lint": "eslint -c .eslintrc --ext .ts ./src",
"start": "npm run build && electron ./dist/main.js"
},
"repository": "https://github.com/electron/electron-quick-start-typescript",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo",
"typescript"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.33.0",
"#typescript-eslint/parser": "^4.33.0",
"electron": "^16.0.2",
"eslint": "^7.32.0",
"typescript": "^4.5.2"
},
"dependencies": {
"node-fetch": "^2.6.1"
}
}
Found the answer. For anyone else having the same issue this resolved the issue -
Make sure nodeIntegration is enabled in main.js
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, "preload.js"),
},
Index.html
replace:
<script src="./dist/renderer.js"></script>
with:
<script>
require("./dist/renderer.js");
</script>

Neither es6 nor es5 syntax allowed for imports in firebase cloud functions

I've been tripped up by the No imports inside a module error and similar errors more times than I can count. Honestly, I have no idea what it means and it seems to be pretty arbitrary as I've tried adding module rules, removing them, using only es5, using only es6, and nothing seems to be consistent.
Currently I'm trying to use the cross-blob package so I can save a raw SVG as a file, as Blob is not supported in es5 as far as I can tell. My functions are crashing with the following error:
Must use import to load ES Module: /path/to/cross-blob require() of ES modules is not supported.
I'm using that module as follows:
userActions.ts
import { createAvatar } from "#dicebear/avatars"; // this worked fine
import * as style from "#dicebear/avatars-bottts-sprites"; // this worked fine
import Blob from "cross-blob"; // this did not
export const createNewProfileImage = () => {
const profileImageSvg = createAvatar(style);
const blob = new Blob([profileImageSvg], { type: "image/svg+xml" });
// more code
As you can see, no require(). It suggest I remove "type": "module" from my package.json, but it's not used in my package.json.
I'm then importing that fn into my index.ts file as follows:
index.js
import { getBitcoinPrice, getAdviceSlip, getRandomAnimal } from "./callApis"; // works fine
import { createNewProfileImage } from "./userActions"; // works fine if I don't use cross-blob
const createNewUser = functions
.region("europe-west1")
.auth.user()
.onCreate(async (user: UserRecord) => {
const svg = createNewProfileImage();
// more code
I've also tried switching to require statements, but that then errors out with Require statement not part of import statement.
package.json
{
"name": "functions",
"scripts": {
"lint": "eslint --ext .js,.ts .",
"build": "tsc",
"emulate": "npm run build -- --watch | firebase emulators:start --import ../db",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "lib/index.js",
"dependencies": {
"#dicebear/avatars": "^4.10.0",
"#dicebear/avatars-bottts-sprites": "^4.10.0",
"axios": "^0.23.0",
"cross-blob": "^3.0.0",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1"
},
"devDependencies": {
"#types/node": "^16.7.13",
"#typescript-eslint/eslint-plugin": "^3.9.1",
"#typescript-eslint/parser": "^3.8.0",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-import": "^2.22.0",
"firebase-functions-test": "^0.2.0",
"typescript": "^3.8.0"
},
"private": true
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017",
"typeRoots": ["node_modules/#types"],
"moduleResolution": "node"
},
"compileOnSave": true,
"include": [
"src"
]
}

NodeJS problems with imports when transpiling from typescript

I have implemented simple rest api with nodejs and connection to database via typeorm. Here are some snippets of code which I wrote:
import {
Entity,
PrimaryGeneratedColumn,
Column,
Unique,
CreateDateColumn,
UpdateDateColumn
} from "typeorm";
import { Length, IsNotEmpty } from "class-validator";
import bcrypt from "bcryptjs";
#Entity()
#Unique(["username"])
export class User {
#PrimaryGeneratedColumn()
public id: number;
#Column()
#Length(4, 20)
username: string;
}
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"emitDecoratorMetadata": true
},
"lib": [
"es2015"
]
}
package.json
{
"name": "node-with-ts",
"version": "1.0.0",
"description": "",
"main": "dist/app.js",
"scripts": {
"start": "tsc && node dist/app.js",
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"prod": "node ./dist/app.js",
"build": "npm install && tsc -p .",
"reset": "rm -rf node_modules/ && rm -rf dist/ && npm run build",
"migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express": "^4.16.1",
"#types/node": "^12.7.5",
"nodemon": "^1.19.2",
"ts-node": "8.4.1",
"tslint": "^5.12.1",
"typescript": "^3.3.3"
},
"dependencies": {
"#types/bcryptjs": "^2.4.2",
"#types/body-parser": "^1.17.0",
"#types/cors": "^2.8.4",
"#types/helmet": "0.0.42",
"#types/jsonwebtoken": "^8.3.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.1",
"class-validator": "^0.9.1",
"cors": "^2.8.5",
"express": "4.17.1",
"helmet": "^3.21.1",
"jsonwebtoken": "^8.4.0",
"reflect-metadata": "^0.1.13",
"sqlite3": "^4.1.0",
"ts-node-dev": "^1.0.0-pre.32",
"typeorm": "^0.2.12"
}
}
I have pasted lots of code because I have no idea what is wrong. I am tryinf to run app via npm run start and it throws below error:
> tsc && node dist/app.js
/Users/workspace/node_typescript_project/src/entity/User.ts:1
(function (exports, require, module, __filename, __dirname) { import {
^^^^^^
SyntaxError: Unexpected token import
Although I able to build to project and it generates js codes but when it comes to run application it throws errors.
Your entities are probably not being referenced correctly in your Typeorm config file.
Try to see if you can get it to work with the following ormconfig.js file (pay special attention to the entities property:
// ormconfig.js at root of project
const isDevelopment = process.env.NODE_ENV === 'development';
module.exports = {
type: 'mysql',
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_TCP_PORT,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
synchronize: isDevelopment,
logging: isDevelopment,
entities: [
isDevelopment ? `src/**/*.entity.ts` : `dist/**/*.entity.js`,
],
migrations: [`src/migration/**/*.ts`],
subscribers: ['src/subscriber/**/*.ts'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'src/migration',
subscribersDir: 'src/subscriber',
},
};
With this setup, I have ts-node working directly with my Typescript source files, and only in production do I use tsc to build. When building for prod, I need to reference the .js files inside of the dist folder.
I am trying to replicate the issue but couldn't replicate it. Just created a sample repo for above code.
https://github.com/pktippa/stackoverflow-questions/tree/master/58148222
Try a different import syntax, eg.:
import { bcrypt } from "bcryptjs";
Other import syntax examples can be found here.
Node.js does not handle ES6 syntax, with imports etc.
For that you have to transpile your ES6 code to ES5, you can do it with Babel => https://github.com/babel/example-node-server
If you don't want to use Babel, you can simply replace import by require:
const bcrypt = require("bcryptjs"); // same as 'import * as bcrypt from "bcryptjs";'

Getting error message Module build failed (from ./node_modules/sass-loader/dist/cjs.js) when running npm serve

I'm working on a Vue/Vuetify project for quite some time now. It all worked fine until yesterday. I had problems with using the <v-simple-table> vuetify component, so I decided to run npm install and re-install vuetify: bad idea.
The problem is that I get the following error multiple times when running npm run serve:
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
ValidationError: Invalid options object. Sass Loader has been initialised using an options object that does not match the API schema.
- options has an unknown property 'indentedSyntax'. These properties are valid:
object { implementation?, sassOptions?, prependData?, sourceMap?, webpackImporter? }
at validate (C:\Users\Jeroen\Documents\favourite_xi\node_modules\sass-loader\node_modules\schema-utils\dist\validate.js:49:11)
at Object.loader (C:\Users\Jeroen\Documents\favourite_xi\node_modules\sass-loader\dist\index.js:36:28)
# ./node_modules/vuetify/src/components/VCalendar/mixins/calendar-with-events.sass 4:14-225 14:3-18:5 15:22-233
# ./node_modules/vuetify/lib/components/VCalendar/mixins/calendar-with-events.js
# ./node_modules/vuetify/lib/components/VCalendar/VCalendar.js
# ./node_modules/vuetify/lib/components/VCalendar/index.js
# ./node_modules/vuetify/lib/components/index.js
# ./node_modules/vuetify/lib/index.js
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.178.115:8080/sockjs-node ./node_modules/#vue/cli-service/node_modules/webpack/hot/dev-server.js ./src/main.js
My main.js file:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Vuetify from 'vuetify/lib'
import 'vuetify/dist/vuetify.min.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(BootstrapVue)
Vue.use(Vuetify, {
theme: {
"primary": "#FFCA28",
"secondary": "#1976D2",
"accent": "#82B1FF",
"error": "#FF5252",
"info": "#2196F3",
"success": "#4CAF50",
"warning": "#FB8C00"
}
})
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
I've already looked at multiple posts and they all advise to run npm rebuild node-sass (both regularly as in admin-mode), delete the node-modules folder, re-install sass-loader, but nothing worked so far.
Is there something wrong in my main.js maybe?
Thanks in advance! Let me know if I need to post more of my code or additional information.
Edit: added package.json
{
"name": "favourite_xi",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"bootstrap": "^4.3.1",
"bootstrap-vue": "^2.0.0-rc.22",
"core-js": "^2.6.5",
"node-sass": "^4.12.0",
"stylus": "^0.54.7",
"stylus-loader": "^3.0.2",
"uuid": "^3.3.3",
"vue": "^2.6.10",
"vue-cool-select": "^2.10.2",
"vue-flip": "^0.3.0",
"vue-responsive-text": "^0.1.4",
"vue-router": "^3.0.3",
"vuetify": "^2.0.16",
"vuex": "^3.1.1"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.10.1",
"#vue/cli-plugin-babel": "^3.8.0",
"#vue/cli-plugin-eslint": "^3.8.0",
"#vue/cli-service": "^3.8.0",
"#vue/eslint-config-standard": "^4.0.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"sass-loader": "^8.0.0",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.39.3"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"#vue/standard"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}
This could be result of upgrading sass-loader from v7.x to v8.x
As stated in release notes, they'v made significant changes to configuration
Check your vue.config.js - if you find something like this:
module.exports = {
css: {
loaderOptions: {
sass: {
....some options here...
}
}
}
}
change it to:
module.exports = {
css: {
loaderOptions: {
sass: {
sassOptions: {
....some options here...
}
}
}
}
}
I am not sure if it's of any use but my npm run build errors at the color codes in theme. When I comment out the color code lines it builds without error:
Vue.use(Vuetify, {
theme: {
"primary": "#FFCA28",
"secondary": "#1976D2",
"accent": "#82B1FF",
"error": "#FF5252",
"info": "#2196F3",
"success": "#4CAF50",
"warning": "#FB8C00"
}
})

Categories