Object prototype may only be an object or null wink ошибка как исправить

TypeError: Object prototype may only be an Object or null: undefined

I got some error in my project.
I’m using vuejs, typescript and jest.

It’s just simple code and I tried to unit test with jest, but It have some error. Here is my test code.

///<reference path="../../../../node_modules/@types/jest/index.d.ts"/>
// https://vue-test-utils.vuejs.org/kr/s
import { mount } from "vue-test-utils";
import HelloWorld from './HelloWorld.vue';

describe('[HelloWorld]', function () {
  let cmp: any;

  beforeEach(() => {
    cmp = mount(HelloWorld);
  });

  it("Check vue instance", () => {
    expect(cmp.isVueInstance()).toBeTruthy();
  });

  it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });
});

and Here is vue file

   <template>
   <div class="hello">
       <h1>{{ msg }}</h1>
       <img src="/assets/logo.png">
       <button @click="clickHandler">
         button
       </button>
     </div>
   </template>

   <script lang="ts">
   import Vue from "vue";
   import Component from "vue-class-component";

   interface HelloWorldInterface {
     msg: string;
     clickHandler(): void;
   }

   @Component({})
   export default class HelloWorld extends Vue implements HelloWorldInterface {
     msg = "Hello!!";
     clickHandler() {
       window.alert(this.msg);
     }
   }
   </script>

Here is error logs with picture.

asked Feb 26, 2018 at 15:55

Younghoon Kim's user avatar

1

You should set esModuleInterop = true for your tsconfig.json or your own tsconfig just for jest

answered Jul 20, 2018 at 11:46

Hoang Vu's user avatar

Hoang VuHoang Vu

811 silver badge4 bronze badges

The problem seems to be how Vue2 exposes itself, so import Vue from "vue" causes this error.

I fixed it by using ‘vue-property-decorator’ like this:

import { Vue, Component, Prop } from 'vue-property-decorator';

So what does ‘vue-property-decorator’ do? It imports and then exports Vue not as default but named export. I guess you could do that in your own code, if you wanted.

import Vue, { PropOptions, WatchOptions } from 'vue';
...
export { Component, Vue, mixins as Mixins };

answered Apr 9, 2020 at 7:32

Reynicke's user avatar

ReynickeReynicke

1,3051 gold badge10 silver badges20 bronze badges

For me, using import * as Vue from "vue" instead of import Vue from "vue" fixed the problem for my projects with a similar setup, i.e.:

//import Vue from "vue";
import * as Vue from "vue";
import Component from "vue-class-component";

interface HelloWorldInterface {
  msg: string;
  clickHandler(): void;
}

@Component
export default class HelloWorld extends Vue implements HelloWorldInterface {
  msg = "Hello!!";
  clickHandler() {
    window.alert(this.msg);
  }
}

It is a lot more cumbersome, but at least it works. I have setup a proof-of-concept example using vue-cli: https://codesandbox.io/s/mjvjw2xw39

Bassie's user avatar

Bassie

9,0227 gold badges59 silver badges138 bronze badges

answered Apr 5, 2018 at 7:19

Terry's user avatar

TerryTerry

61.4k15 gold badges90 silver badges114 bronze badges

Not

 it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });

Should be

it("message is Hello", () => {
    expect(cmp.msg).toEqual('Hello!!');
  });

answered Feb 26, 2018 at 16:11

аlex dykyі's user avatar

аlex dykyіаlex dykyі

5,3111 gold badge28 silver badges38 bronze badges

I solved the problem by removing lang=»ts» from tag

answered Mar 31, 2020 at 8:02

Александр Братко's user avatar

Checkout this link below, it really helped me resolve CIRCULAR DEPENDENCY issue with the command
npx madge --circular --extensions ts ./

Link:
To Detect Circular Dependency in you package

Neverthless I’m still getting the Error..!! :(

answered Aug 10, 2020 at 11:36

B. K.'s user avatar

B. K.B. K.

536 bronze badges

TypeError: Object prototype may only be an Object or null: undefined

I got some error in my project.
I’m using vuejs, typescript and jest.

It’s just simple code and I tried to unit test with jest, but It have some error. Here is my test code.

///<reference path="../../../../node_modules/@types/jest/index.d.ts"/>
// https://vue-test-utils.vuejs.org/kr/s
import { mount } from "vue-test-utils";
import HelloWorld from './HelloWorld.vue';

describe('[HelloWorld]', function () {
  let cmp: any;

  beforeEach(() => {
    cmp = mount(HelloWorld);
  });

  it("Check vue instance", () => {
    expect(cmp.isVueInstance()).toBeTruthy();
  });

  it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });
});

and Here is vue file

   <template>
   <div class="hello">
       <h1>{{ msg }}</h1>
       <img src="/assets/logo.png">
       <button @click="clickHandler">
         button
       </button>
     </div>
   </template>

   <script lang="ts">
   import Vue from "vue";
   import Component from "vue-class-component";

   interface HelloWorldInterface {
     msg: string;
     clickHandler(): void;
   }

   @Component({})
   export default class HelloWorld extends Vue implements HelloWorldInterface {
     msg = "Hello!!";
     clickHandler() {
       window.alert(this.msg);
     }
   }
   </script>

Here is error logs with picture.

asked Feb 26, 2018 at 15:55

Younghoon Kim's user avatar

1

You should set esModuleInterop = true for your tsconfig.json or your own tsconfig just for jest

answered Jul 20, 2018 at 11:46

Hoang Vu's user avatar

Hoang VuHoang Vu

811 silver badge4 bronze badges

The problem seems to be how Vue2 exposes itself, so import Vue from "vue" causes this error.

I fixed it by using ‘vue-property-decorator’ like this:

import { Vue, Component, Prop } from 'vue-property-decorator';

So what does ‘vue-property-decorator’ do? It imports and then exports Vue not as default but named export. I guess you could do that in your own code, if you wanted.

import Vue, { PropOptions, WatchOptions } from 'vue';
...
export { Component, Vue, mixins as Mixins };

answered Apr 9, 2020 at 7:32

Reynicke's user avatar

ReynickeReynicke

1,3051 gold badge10 silver badges20 bronze badges

For me, using import * as Vue from "vue" instead of import Vue from "vue" fixed the problem for my projects with a similar setup, i.e.:

//import Vue from "vue";
import * as Vue from "vue";
import Component from "vue-class-component";

interface HelloWorldInterface {
  msg: string;
  clickHandler(): void;
}

@Component
export default class HelloWorld extends Vue implements HelloWorldInterface {
  msg = "Hello!!";
  clickHandler() {
    window.alert(this.msg);
  }
}

It is a lot more cumbersome, but at least it works. I have setup a proof-of-concept example using vue-cli: https://codesandbox.io/s/mjvjw2xw39

Bassie's user avatar

Bassie

9,0227 gold badges59 silver badges138 bronze badges

answered Apr 5, 2018 at 7:19

Terry's user avatar

TerryTerry

61.4k15 gold badges90 silver badges114 bronze badges

Not

 it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });

Should be

it("message is Hello", () => {
    expect(cmp.msg).toEqual('Hello!!');
  });

answered Feb 26, 2018 at 16:11

аlex dykyі's user avatar

аlex dykyіаlex dykyі

5,3111 gold badge28 silver badges38 bronze badges

I solved the problem by removing lang=»ts» from tag

answered Mar 31, 2020 at 8:02

Александр Братко's user avatar

Checkout this link below, it really helped me resolve CIRCULAR DEPENDENCY issue with the command
npx madge --circular --extensions ts ./

Link:
To Detect Circular Dependency in you package

Neverthless I’m still getting the Error..!! :(

answered Aug 10, 2020 at 11:36

B. K.'s user avatar

B. K.B. K.

536 bronze badges

@Hunta
I just create a blank new project with media native plugin.
when I run «npm install @angular/cli@8.3.12», I got your same error message when build a production file.
when I run «npm install @angular/cli@5.2.11», build error gone but mp3 fail to play.

here is my package.json:

{
«name»: «myApp»,
«version»: «0.0.1»,
«author»: «Ionic Framework»,
«homepage»: «http://ionicframework.com/»,
«private»: true,
«scripts»: {
«start»: «ionic-app-scripts serve»,
«clean»: «ionic-app-scripts clean»,
«build»: «ionic-app-scripts build»,
«lint»: «ionic-app-scripts lint»
},
«dependencies»: {
«@angular/animations»: «5.2.11»,
«@angular/cli»: «^8.3.12»,
«@angular/common»: «5.2.11»,
«@angular/compiler»: «5.2.11»,
«@angular/compiler-cli»: «^8.2.11»,
«@angular/core»: «5.2.11»,
«@angular/forms»: «5.2.11»,
«@angular/http»: «5.2.11»,
«@angular/platform-browser»: «5.2.11»,
«@angular/platform-browser-dynamic»: «5.2.11»,
«@ionic-native/core»: «~4.20.0»,
«@ionic-native/media»: «^4.20.0»,
«@ionic-native/splash-screen»: «~4.20.0»,
«@ionic-native/status-bar»: «~4.20.0»,
«@ionic/storage»: «2.2.0»,
«cordova-android»: «^8.1.0»,
«cordova-plugin-device»: «^2.0.2»,
«cordova-plugin-file»: «^6.0.2»,
«cordova-plugin-ionic-keyboard»: «^2.2.0»,
«cordova-plugin-ionic-webview»: «^4.1.2»,
«cordova-plugin-media»: «^5.0.3»,
«cordova-plugin-splashscreen»: «^5.0.2»,
«cordova-plugin-statusbar»: «^2.4.2»,
«cordova-plugin-whitelist»: «^1.3.3»,
«cordova-res»: «^0.8.0»,
«ionic-angular»: «3.9.5»,
«ionicons»: «3.0.0»,
«rxjs»: «5.5.11»,
«sharp»: «^0.23.1»,
«sw-toolbox»: «3.6.0»,
«zone.js»: «0.8.29»
},
«devDependencies»: {
«@ionic/app-scripts»: «3.2.2»,
«typescript»: «~2.6.2»
},
«description»: «An Ionic project»,
«cordova»: {
«plugins»: {
«cordova-plugin-media»: {},
«cordova-plugin-whitelist»: {},
«cordova-plugin-statusbar»: {},
«cordova-plugin-device»: {},
«cordova-plugin-splashscreen»: {},
«cordova-plugin-ionic-webview»: {
«ANDROID_SUPPORT_ANNOTATIONS_VERSION»: «27.+»
},
«cordova-plugin-ionic-keyboard»: {}
},
«platforms»: [
«android»
]
}
}

#javascript #node.js #es6-modules #vite #filestack

Вопрос:

Я использую filestack-js в проекте Rails, который поставляется в комплекте с Vite. Все работает так, как ожидалось, пока я не включу модуль ESM для filestack-js библиотеки, в данном случае в контроллер StimulusJS:

 import { Controller } from "stimulus";

import * as filestack from "filestack-js";

export default class extends Controller {
  // some irrelevant implementation code that calls filestack.init(...)
}
 

Загрузка вышеуказанного файла контроллера в браузере вызывает ошибку:

 tslib.es6.js:25 Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at setPrototypeOf (<anonymous>)
    at __extends (tslib.es6.js:25)
    at http.ts:43
    at node_modules/filestack-js/build/module/lib/request/adapters/http.js (http.ts:64)
    at __init (chunk-IHTDASF6.js?v=1616a449:14)
    at request_adapter.node.ts:17
 

Это ошибка, вызванная браузером при работе в среде разработки, при использовании Vite для создания и обслуживания модулей ES непосредственно в браузере. Он обрабатывает компиляцию машинописного текста. Удаление import * as filestack бита устраняет ошибку (но, очевидно, нарушает функциональность класса).

Мои поиски в Google, похоже, предполагают, что это может быть проблемой циклической зависимости. Трассировка стека браузера указывает на файл в filestack-js библиотеке:

 // src/lib/request/adapters/http.ts

import * as url from 'url';
import * as zlib from 'zlib';
import Debug from 'debug';

import { AdapterInterface } from './interface';
import { getVersion } from '../../utils';
import * as Stream from 'stream'; // <---------- Stream imported here
import { FsRequestOptions, FsResponse } from '../types';
import * as utils from '../utils';
import { prepareData, parseResponse, combineURL, set as setHeader, normalizeHeaders } from './../helpers';
import { FsRequestErrorCode, FsRequestError } from '../error';
import { FsHttpMethod } from './../types';

const HTTPS_REGEXP = /https:?/;
const HTTP_CHUNK_SIZE = 16 * 1024;
const MAX_REDIRECTS = 10;
const CANCEL_CLEAR = `FsCleanMemory`;
const debug = Debug('fs:request:http');

class HttpWritableStream extends Stream.Writable {
  // omitted class definition
}
 

Где Stream.Writable на самом деле не определено из-за проблемы циклической зависимости. Я понятия не имею, как это могло произойти или, похоже, повлияло только на меня.

Это не проблема, о которой сообщалось в отслеживателе проблем filestack-js.

Отладка в браузере и локальное клонирование/связывание репозитория подтвердили , что Stream.Writable это возвращается undefined , но я недостаточно знаю о JS, чтобы понять, почему. Предположительно, это обычно происходит из-за циклической зависимости, но я не уверен, как модуль nodejs Stream будет иметь циклические зависимости от случайной библиотеки, например filestack-js . Я также достаточно неопытен в мире JS, чтобы точно понять, что значит использовать библиотеку NodeJS, как Stream в модуле браузера, — filestack-js в ней есть как браузерные модули, так и модули CommonJS/NodeJS, поэтому я не уверен, как/связаны ли они или взаимодействуют.

Вот как Stream выглядит объект при входе в консоль браузера. Очевидно, что что-то было импортировано, но Writable не является свойством того, что было импортировано:

консоль браузера

FWIW это происходит в Chrome и Firefox, последних версиях каждого из них.

Я также попытался использовать dpdm для анализа проекта filestack-js на наличие циклических зависимостей. Он нашел некоторые, но не похоже, что они вызывают ошибки, и, похоже, явно исключаются библиотеки узлов и другие библиотеки зависимостей.

Комментарии:

1. Хорошо, я вижу, что это может быть связано с тем фактом, что Vite использует накопительный пакет под капотом, и этот накопительный пакет может не справляться с определенными циклическими зависимостями, существующими в библиотеках NodeJS? это репозиторий существует, и кажется, что он может быть разработан для решения такого рода проблем, но, похоже, он не работает для меня.

2. Действительно ли этот стимул и ваш собственный класс необходимы для того, чтобы вызвать проблему, или это уже происходит, если все, что вы делаете, — это импортируете filestack-js библиотеку?

3. @Bergi Я могу подтвердить, что это не имеет отношения к делу. Просто так получилось, что я пользуюсь библиотекой именно там. Извини, что я не ясно выразился.

4. В этом случае я бы определенно сообщил об этом как об ошибке в их системе отслеживания проблем. Тем более, что документация утверждает, что работает с накопительным пакетом из коробки. Однако вам следует поделиться своей конфигурацией свертки

5. Ого, я пропустил эту ссылку на свертку. До сих пор я не решался опубликовать проблему, потому что у меня нет простого решения, но, думаю, я мог бы придумать более простое. Спасибо.

Ответ №1:

Хорошо, я думаю, что решил свою проблему, но я не эксперт, поэтому я попытаюсь объяснить, в чем была проблема. Не стесняйтесь вступать в разговор с разъяснениями, если вам лучше известно.

Это было вызвано filestack-js интенсивным использованием библиотек nodejs. Исторически сложилось так, что Webpack v4 заполнил множество распространенных библиотек NodeJS для использования в браузере, полностью прозрачных для большинства разработчиков. Это прекрасно работало, но было полным волшебством.

Накопительный пакет и, кстати, Webpack v5 не выполняют этого заполнения, поэтому любые библиотеки NodeJS, используемые библиотеками «ESM» из NPM, которые напрямую не совместимы с современными браузерами, просто сломаются. Чтобы заполнить это вручную, мне пришлось поручить Vite amp; Rollup присвоить псевдоним имени модуля nodejs stream чему-то, что напрямую совместимо с браузерами, и установить его. Чтобы сделать это, я:

 yarn add --dev stream-browserify
 

И добавил следующее к моему vite.config.js :

 // ...
resolve: {
  alias: {
    stream: "stream-browserify",
  },
},
// ...
 

Должен быть очень похожий (но другой) способ сообщить свертке, чтобы сделать это, потому что здесь я делаю это через конфигурацию Vite.

Для дополнительного контекста вот проблема GitHub, которую я открыл в filestack-js репо: https://github.com/filestack/filestack-js/issues/458

Ответ №2:

Привет, я только начал с TypeScript, и я попытался скопировать javascript в TypeScript и изменил материал, чтобы он был более объектно-ориентированным. Теперь я пытаюсь запустить его с помощью cmd и команды ns-node.

private username:string;
           ^
TypeError: Object prototype may only be an Object or null: undefined

Эта ошибка не имеет никакого смысла, поэтому я погуглил и увидел, что проблема может заключаться в импорте проекта. Я перепробовал каждую душу на разных сайтах, и они не помогли.

Итак, мой код:

import { Entity } from './Entity';
import { Bullet } from './Bullet';

import * as fs from "fs";
export class Player extends Entity{

private username:string;
protected pressingRight:boolean ;
protected pressingLeft:boolean ;
...
}

Так в чем может быть проблема? Тебе за твою помощь

РЕДАКТИРОВАТЬ:

    import {Point} from "./Point";
    import {Bullet} from "./Bullet";
import {Player} from "./Player";
export class Entity{

protected x:number;
protected y:number;
protected spdX:number = 0;
protected spdY:number = 0;
protected id:number;
protected map:string;


protected static initPack = {player:[],bullet:[]};
protected static removePack = {player:[],bullet:[]};

 constructor(x:number,y:number,id:number,map:string){
    this.x = x;
    this.y=y;
    this.id=id;
    this.map=map;
 }
...}

И Bullet.ts:

    import {Entity} from './Entity';
import {Player} from './Player';
export class Bullet extends Entity{

private angle:number;
private parentID:number;
private timer:number = 0;
private toRemove:boolean=false;

public static list={};

constructor(x:number,y:number,map:string,parentId:number,angle:number,id:number){
    super(x,y,id,map);
    this.angle = angle;
    this.spdX= Math.cos(angle/180*Math.PI) * 10;
    this.spdY= Math.sin(angle/180*Math.PI) * 10;
    this.parentID = parentId;

    Bullet.list[this.id] = self;
    Bullet.initPack.bullet.push(this.getInitPack());
}

1 ответ

Лучший ответ

У вас циклический импорт. В зависимости от того, с какого файла вы начинаете, когда ts-node достигает импорта файла, который уже находится в процессе загрузки, он продолжит этот импорт, даже если загрузка импортированного файла не завершена. Вот как можно обойти import { Entity } from './Entity';, а Entity все еще может быть неопределенным.

Если Entity.ts не требуется доступ к классу Player во время загрузки файла, попробуйте переместить строку import { Player } from './Player'; в конец Entity.ts.


6

Matt McCutchen
11 Авг 2018 в 23:48

To add to this, the actual problem here with the circular dependency is because one of resources that have not loaded before they are used. You will also get this error if your resources are loading out of order.

Consider this example that uses gulp to compile:

// File Parent.ts
export class Parent {
    public prop: string = "prop";
}
//File Child.ts
export class Child extends Parent {
    public prop2: string = "prop2";
}

and the gulp to compile

gulp.task('compile-js', function () {
return gulp.src(['code/Child.js', 'code/Parent.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('app.bundle.js'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('app/build'));
});

The output file app.bundle.js will error with «Uncaught TypeError: Object prototype may only be an Object or null: undefined» because the resulting code will first execute the creation of the Child class (which has the dependency on the Parent class) before the parent class has been loaded.

If you look at the resulting javascript you will get:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Child = /** @class */ (function (_super) {
    __extends(Child, _super);
    function Child() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.prop2 = "prop2";
        return _this;
    }
    return Child;
}(Parent));
var Parent = /** @class */ (function () {
    function Parent() {
        this.prop = "prop";
    }
    return Parent;
}());

And when you run this you will get:

Uncaught TypeError: Object prototype may only be an Object or null: undefined
at setPrototypeOf ()

To fix this, simply change the order of the resources in your gulp file or whatever method you are using to prepare or load the javascript for the page.

return gulp.src(['code/Parent.js', 'code/Child.js'])

There are many ways that this can be dealt with, this is just an example to help you understand the problem and how you might fix it. Whichever way you find to fix the problem, in the end, the error is asking the javascript engine to do something you haven’t yet given instructions for at the time of execution.

Hope this helps,
Cheers

Below if I import Entity I get the posts’s subject error (TypeError: Object prototype may only be an Object or null: undefined), but if I replace the import with the actual Entity declaration the code runs fine.

Stackblitz demo here.

This is Customer.ts in the form that produces the error when I run the code with ts-node:

index.ts

export { Customer } from "./Customer";
export { Entity } from "./Entity";

Customer.ts

import { Entity } from "./index";

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}

Entity.ts

export abstract class Entity {
  id?: string;
}    

Run.ts (The test code)

import {Customer} from "./";

let c = new Customer({
  name: "Bob"
});
console.log(c);

If I replace the Entity import with the declaration like this:

export abstract class Entity {
  id?: string;
}    

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}

Then Run.ts logs this:

Customer { sku: undefined }

In other words it runs fine and produces no errors. Thoughts?

asked Nov 2, 2018 at 16:48

Ole's user avatar

OleOle

40.5k57 gold badges186 silver badges348 bronze badges

4

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

As you saw, changing Customer.ts to import from ./Entity directly instead of ./index breaks the cycle, and everything works as expected. Another solution would be to reverse the order of imports in index.ts.

answered Nov 2, 2018 at 17:42

Matt McCutchen's user avatar

Matt McCutchenMatt McCutchen

28.3k2 gold badges67 silver badges74 bronze badges

2

This is not directly an answer to the example above, but I got the same error message when I had Vue and Parcel, and this kind of code:

class Proxy {}

class MyProxy extends Proxy {}

After some lengthy debugging, it turned out that there seems to be some class name conflict with the name «Proxy», maybe from Parcel. After I renamed the super class as «AbstractProxy» or anything else than «Proxy», it started to work.

answered Mar 6, 2022 at 11:09

PHZ.fi-Pharazon's user avatar

You can try this command and check the application:

  1. ng update @angular/cli @angular/core --force
  2. npm install
  3. ng serve -o

ingvar's user avatar

ingvar

4,1194 gold badges16 silver badges29 bronze badges

answered Sep 14, 2019 at 9:32

Kaushik Vaghani's user avatar

Привет, я только начал с TypeScript, и я попытался скопировать javascript в TypeScript и изменил материал, чтобы он был более объектно-ориентированным.
Теперь я пытаюсь запустить его с помощью cmd и команды ns-node.

private username:string;
           ^
TypeError: Object prototype may only be an Object or null: undefined

Эта ошибка не имеет никакого смысла, поэтому я погуглил и увидел, что проблема может заключаться в импорте проекта. Я перепробовал каждую душу на разных сайтах, и они не помогли.

Итак, мой код:

import { Entity } from './Entity';
import { Bullet } from './Bullet';

import * as fs from "fs";
export class Player extends Entity{

private username:string;
protected pressingRight:boolean ;
protected pressingLeft:boolean ;
...
}

Так в чем может быть проблема? Тебе за твою помощь

Обновлено:

    import {Point} from "./Point";
    import {Bullet} from "./Bullet";
import {Player} from "./Player";
export class Entity{

protected x:number;
protected y:number;
protected spdX:number = 0;
protected spdY:number = 0;
protected id:number;
protected map:string;


protected static initPack = {player:[],bullet:[]};
protected static removePack = {player:[],bullet:[]};

 constructor(x:number,y:number,id:number,map:string){
    this.x = x;
    this.y=y;
    this.id=id;
    this.map=map;
 }
...}

И Bullet.ts:

    import {Entity} from './Entity';
import {Player} from './Player';
export class Bullet extends Entity{

private angle:number;
private parentID:number;
private timer:number = 0;
private toRemove:boolean=false;

public static list = {};

constructor(x:number,y:number,map:string,parentId:number,angle:number,id:number){
    super(x,y,id,map);
    this.angle = angle;
    this.spdX= Math.cos(angle/180*Math.PI) * 10;
    this.spdY= Math.sin(angle/180*Math.PI) * 10;
    this.parentID = parentId;

    Bullet.list[this.id] = self;
    Bullet.initPack.bullet.push(this.getInitPack());
}

Answer by Lucian Melton

3) Open the packages.json of your main project and change the following versions of dependencies:,

Is centripetal acceleration almost perpendicular to velocity or it is exactly perpendicular to velocity?

,Once removed the circular dependency, everything worked fine.,I had the same problem with my [email protected] project after updating the CLI globally to version 8 and solve it by upgrading angular in my project to the latest version by running this command in my project directory:

I had the same problem with my [email protected] project after updating the CLI globally to version 8 and solve it by upgrading angular in my project to the latest version by running this command in my project directory:

ng update @angular/cli @angular/core

You can also use the allow-dirty flag to bypass the repo check:

ng update @angular/cli @angular/core --allow-dirty

Answer by Mckenna Casey

Hi:
I am getting error:
An unhandled exception occurred: Object prototype may only be an Object or null: undefined
when trying to build project in CI.
I found out the following dependencies while testing to build project:,https://stackoverflow.com/questions/57421582/typeerror-object-prototype-may-only-be-an-object-or-null-undefined-angular-8,Search or submit bugs against the npm CLI or any of our other maintained OSS projects,We have empty node_modules and no package-lock.json file.
So I do npm install (it will create package-lock) then ng build —prod

Hi:
I am getting error:
An unhandled exception occurred: Object prototype may only be an Object or null: undefined
when trying to build project in CI.
I found out the following dependencies while testing to build project:

An unhandled exception occurred: Object prototype may only be an Object or null: undefined

Answer by Zola Reed

Getting the error «Object prototype may only be an Object or null: undefined» when running «ionic serve»,Steps to reproduce:
Started getting this cryptic error message out of nowhere when I upgraded the Ionic CLI, ionic-app-scripts, and ionic-angular to the latest versions.,In my case there was a circular reference problem too. However, it was the export order on an index.ts file that was causing the problem.,Open the packages.json of your main project and change the following versions of dependencies:
«@angular/*»
«@ionic-native/*»
«rxjs»
Also, replace the «scripts» part.

Runtime Error
Object prototype may only be an Object or null: undefined
Stack
TypeError: Object prototype may only be an Object or null: undefined
    at setPrototypeOf (<anonymous>)
    at webpackJsonp.57.__extends (http://localhost:8100/build/main.js:5954:9)
    at http://localhost:8100/build/main.js:5976:5
    at Object.57 (http://localhost:8100/build/main.js:5988:2)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.132 (http://localhost:8100/build/main.js:977:90)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.249 (http://localhost:8100/build/main.js:3218:71)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.130 (http://localhost:8100/build/main.js:724:105)

Answer by Alan Peters

I created new reactJs project to apply BPMN.IO,I have this package.json file

I have this package.json file

"dependencies": {
    "bpmn-font": "^0.10.0",
    "bpmn-js": "^7.4.0",
    "bpmn-js-in-color": "github:bpmn-io/bpmn-js-in-color",
    "diagram-js-minimap": "^2.0.3",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.0",
    "tiny-svg": "^2.2.2",
    "web-vitals": "^0.2.4"
  }

In my App.js

import React, { Fragment, Component } from "react";
import BpmnModeler from "bpmn-js/lib/Modeler";
import { emptyBpmn } from "./diagram.bpmn.jsx";
import bpmnJsInColor from "bpmn-js-in-color";
import minimapModule from "diagram-js-minimap";

import "./vendor/diagram-js.css";
import "bpmn-font/dist/css/bpmn-embedded.css";
import "diagram-js-minimap/assets/diagram-js-minimap.css";

class App extends Component {
  modeler = null;

  saveModelHandler = (event) => {
    event.preventDefault();
  };

  componentDidMount = () => {
    this.modeler = new BpmnModeler({
      container: "#bpmnview",
      additionalModules: [require("bpmn-js-in-color")],
      keyboard: { bindTo: document },
    });

    this.newBpmnDiagram();
  };

  newBpmnDiagram = () => {
    this.openBpmnDiagram(emptyBpmn);
  };

  openBpmnDiagram = async (xml) => {
    await this.modeler.importXML(xml);
    var canvas = this.modeler.get("canvas");
    canvas.zoom("fit-viewport");
  };

  render = () => {
    return (
      <Fragment>
        <div
          id="bpmnview"
          style={{ width: "100%", height: "100vh", float: "left" }}
        ></div>
      </Fragment>
    );
  };
}

export default App;

When I enter npm start . It throws error

 **TypeError: Object prototype may only be an Object or null: undefined**
inherits
**node_modules/inherits/inherits_browser.js:6**
  3 | module.exports = function inherits(ctor, superCtor) {
  4 |   if (superCtor) {
  5 |     ctor.super_ = superCtor
> 6 |     ctor.prototype = Object.create(superCtor.prototype, {
    | ^  7 |       constructor: {
  8 |         value: ctor,
  9 |         enumerable: false,


Answer by Emerson Parrish

Hi guys ,
maybe you can help me to investigate this issue …
when I’m running my build like :,ionic cordova run android —release -> have no issues and all good,ionic cordova run android —release -> have no issues and all good,ionic cordova run android —release – prod I got this error and I try to find out what is that :

cli packages: (/usr/local/lib/node_modules)

@ionic/cli-utils  : 1.19.1
ionic (Ionic CLI) : 3.19.1

global packages:

cordova (Cordova CLI) : 8.0.0 

local packages:

@ionic/app-scripts : 3.2.4
Cordova Platforms  : android 6.4.0 ios 4.5.5
Ionic Framework    : ionic-angular 3.9.2

System:

ios-deploy : 1.9.2 
ios-sim    : 5.0.4 
Node       : v10.16.3
npm        : 6.9.0 
OS         : macOS
Xcode      : Xcode 10.3 Build version 10G8 

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : pro

Answer by Berkley Quinn

TypeError: Object prototype may only be an Object or null: undefined
,[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue,[ ] latest
[ ] @next
[x] 3.0.2

I am switching from TDL to Airgram and get this error:

1|hr  | /home/hr/node_modules/airgram/components/TdProvider.js:7
1|hr  |         return extendStatics(d, b);
1|hr  |                ^
1|hr  | TypeError: Object prototype may only be an Object or null: undefined
1|hr  |     at setPrototypeOf (<anonymous>)
1|hr  |     at extendStatics (/home/hr/node_modules/airgram/components/TdProvider.js:7:16)
1|hr  |     at __extends (/home/hr/node_modules/airgram/components/TdProvider.js:10:9)
1|hr  |     at /home/hr/node_modules/airgram/components/TdProvider.js:66:5
1|hr  |     at Object.<anonymous> (/home/hr/node_modules/airgram/components/TdProvider.js:128:2)
1|hr  |     at Module._compile (internal/modules/cjs/loader.js:689:30)
1|hr  |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
1|hr  |     at Module.load (internal/modules/cjs/loader.js:599:32)
1|hr  |     at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
1|hr  |     at Function.Module._load (internal/modules/cjs/loader.js:530:3)

Answer by Hugh McPherson

As you saw, changing Customer.ts to import from ./Entity directly instead of ./index breaks the cycle, and everything works as expected. Another solution would be to reverse the order of imports in index.ts.

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Run.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

index.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Customer.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

index.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

index.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Customer.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

import { Entity } from "./index";

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Entity

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

index.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Entity

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Customer.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

index.ts

As I suspected, your original program has circular imports. Run.ts imports index.ts, which imports Customer.ts, which imports index.ts again. Since index.ts is already in the process of loading and itself depends on Customer.ts, the import { Entity } from "./index"; just binds the Entity of index.ts (which is not set yet) to the Entity of Customer.ts, and execution proceeds even though index.ts isn’t finished loading. Then Entity is undefined at the time you try to extend it. You might argue that a circular import should be an error or that JavaScript engines should use some other algorithm that correctly handles your scenario; I’m not qualified to comment on why the current design was chosen. (Others feel free to add information about this.)

Entity

Понравилась статья? Поделить с друзьями:
  • Error no nvidia display adapters found как исправить
  • Составить предложение со словом тепло как категория состояния
  • Как с ноутбука найти вайфай в ноутбуке
  • Как найти организацию по коду пфр
  • Как найти все пакеты в debian