1

I'm having problems getting aframe 0.7.0 properly working in my angular 4.3.6 (angular-cli 1.0.0) project. Some of the messages I'm getting:

Chrome 61.0.3163 (Windows 10 0.0.0) LOG: '%cA-Frame:warn %cPut the A-Frame <script> tag in the <head> of the HTML *before* the scene to ensure everything for A-Frame is properly registered before they are used from HTML.%c ', 'color: orange', 'color: inherit', 'color: orange'

and: 'a-assets' is not a known element: 1. If 'a-assets' is an Angular component, then verify that it is part of this module. 2. If 'a-assets' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (" lss-aframe-component tats #introScene> <!-- <ng-template appGameScene></ng-template> --> [ERROR ->]<a-assets>

It seems one of the big issues with aframe that is different from other JS libraries is the requirement that it be loaded from the <head> element and not the <body> element.

I have found some partial solutions on stackoverflow here ,here and here, but none of the provided solutions are working across all my 'ng serve' and 'ng test' environments. In particular, I'm having a difficult time getting unit tests to work on components that reference the AFRAME namespace.

What do you need to do to integrate aframe into an Angular2 environment, including unit tests?

2 Answers 2

4

Here is what I had to do in order to get a-frame fully integrated into angular. I'm not saying this is necessarily the best way to do it, or that you will have to do all this. Some people seem to be able to get away with simpler solutions, and if these work for you (e.g. simply adding the aframe lib into polyfill.ts) then go for it. Apparently solutions can vary with angular release, and if you're not running unit tests, then you won't need to do everything I describe here.

The big files you'll need to be concerned with are:

.angular-cli.json
karma.conf.js
src/app/app.module.ts
src/index.html
all your .spec.ts files

ng serve environment

1) To get your 'ng serve' (web) environment to load aframe.js from the head, add the aframe.js lib to 'src/index.html' like so:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>My app</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="../node_modules/aframe/dist/aframe-master.js"></script>
  ...

Note: you do not need to include a script tag for three.js, as aframe will pre-req it in.

Note 2: you can also use 'node_modules'/aframe/build/aframe.js'. 'aframe-master.js' is a more of 'bleeding edge unstable' build, but it works good enough for me.

Note 3 (updated '2018-01-10'): While I seemed to be able to use "../node_modules" with angular 4, with angular5 I had to copy 'aframe-master.js' and 'aframe-master.js.map' into a subdirectory of 'assets' e.g. 'src/assets/libs'. In short, angular 5 seems to require that external js libs be loaded from '/assets' (?).

Typically, you should include javascript libraries in the scripts tag of .angular.cli.json, but if you put them there they won't get loaded from head. My scripts tag is currently empty, but you should put any other js libs there and not in index.html:

cat .angular-cli.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "lss"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
      ],
      "environmentSource": "environments/environment.ts",

Note how scripts is blank and does not contain aframe.js

2) Add 'CUSTOM_ELEMENTS_SCHEMA' to 'src/app/app.module.ts':

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...
entryComponents: [AppComponent, PlaneSceneComponent],
 bootstrap: [AppComponent],
 schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }

Note: CUSTOM_ELEMENTS_SCHEMA allows non-angular tags (e.g <a-scene>) to be used in your angular html.

That's pretty much it if you're not running unit tests. The karma test environment is completety separarate from the standard web-based enviornment. If you're planning on doing unit tests, perform the following additional steps to set up the test environment.

ng test environment

3) Update karma.conf.js to be aware of aframe and three.js and to specify a custom context file:

--> Update 2018-03-08: As of angular cli 1.7.3, 'customContextFile' appears to no longer be honored by angular. It also doesn't seem to be able to read files from node_modules anymore -- you have to put aframe-master.lib under 'src/assets/'. I had to directly edit 'node_modules/@angular/cli/plugins/karma-context.html' like so:

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <!--user add -->
  <script type="text/javascript" src="/base/src/assets/libs/aframe-master.js" crossorigin="anonymous"></script>
  <!--user end -->
</head>

Unfortunately, until I can find a more official way to do achieve this effect, this hack has to be manually performed on each checked out repo, since most people don't check in the node_modules directory. The following worked pre ng-cli 1.7.3:

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    //user add
    customContextFile: './src/environments/context_aframe_ut.html',
    //user end
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [
      { pattern: './src/test.ts', watched: false },
      //user add
      { pattern: 'node_modules/aframe/dist/aframe-master.js', included: false, served: true },
      { pattern: 'node_modules/three/build/three.js', included: false, served: true }
      //user end
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'coverage-istanbul']
              : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Note: the sections of code surrounded by '//user add' and '//user end' blocks. The first defines a new 'context.html' file that we will create that will load aframe.js from the <head> tag. The second defines the aframe and three.js libraries to karma.

4) Create a new karma context html file to load aframe from head.

--> Update 2018-03-08: Note with ang-cli 1.7.3, since 'customContextFile' is no longer honored, you don't have to do this step. Edit 'node_modules/@angular/cli/plugins/karma-context.html' as described in the prior step.

Copy file 'node_modules/karma/static/context.html' to your 'customContextFile' directory defined previously, and modify like so:

<!DOCTYPE html>
<!--
This is the execution context.
Loaded within the iframe.
Reloaded before every execution run.
vt was here 3.
-->
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <!--user add -->
  <!-- <script src="aframe-master.js"></script> -->
  <script src="/base/node_modules/aframe/dist/aframe-master.js"></script>
  <!--user end -->
</head>
<body>
  <!-- The scripts need to be in the body DOM element, as some test running frameworks need the body
       to have already been created so they can insert their magic into it. For example, if loaded
       before body, Angular Scenario test framework fails to find the body and crashes and burns in
       an epic manner. -->
  <script src="context.js"></script>
  <script type="text/javascript">
    // Configure our Karma and set up bindings
    %CLIENT_CONFIG%
    window.__karma__.setupContext(window);

    // All served files with the latest timestamps
    %MAPPINGS%
  </script>
  <!-- Dynamically replaced with <script> tags -->
  %SCRIPTS%
  <script type="text/javascript">
    window.__karma__.loaded();
  </script>
</body>
</html>

Note: the '//user add' and '//user end' sections again.
Note 2: you have to prefix the aframe lib with '/base' in order for karma find it. Note my aborted attempt to get a non-prefixed version to work.
Note 3: (optional) put in some text in the opening comment e.g. 'vt was here' so you can more easily verify Karma is indeed loading your custom context.html.

5) (optional) Verify the updated context.html.

run 'ng test' and inspect the html used by the browser. Verify under node 'iframe.#document.html.head' you have:

<script src="/base/node_modules/aframe/dist/aframe-master.js"></script>

This confirms that the karma is loading aframe from the head.

6) Add 'CUSTOM_ELEMENTS_SCHEMA' to each of your spec.ts files that utilize a-frame:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core"; //<- add
import { RouterTestingModule } from '@angular/router/testing';
import { LoopySurfaceSurfersComponent } from './loopy-surface-surfers.component';
import { AsteroidsGame } from '../inner-games/asteroids/asteroids-game';
import { Ship } from '../inner-games/asteroids/ship';
import { BaseService } from '../services/base.service';
import { UtilsService } from '../services/utils.service';

describe('LoopySurfaceSurfersComponent', () => {
  let component: LoopySurfaceSurfersComponent;
  let fixture: ComponentFixture<LoopySurfaceSurfersComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoopySurfaceSurfersComponent ],
      imports: [RouterTestingModule],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ], // <- add
      providers: [AsteroidsGame, Ship, UtilsService, BaseService,
        THREE.Scene
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoopySurfaceSurfersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

7) You may have to cycle 'ng serve' and 'ng test' in order to pick up on the changes.

Conclusion

As you can see this is not exactly trivial. The big source of problems is the requirement that aframe load from head. I hope this saves someone all the effort I had to go through to get aframe fully integrated into an angular2 environment.

I should also state that I absolutely love A-frame and it works spectacularly well with angular. Running these two frameworks together is a great combo and it's definitely worth the effort, so don't get discouraged if you're having config issues.

1
  • I tiryed to do steps 3 and 4 but it is not working, karma is still showing errors like this: "Object doesn't support property or method 'emit' thrown"
    – vladernn
    May 3, 2019 at 11:44
0

Update for @vt5491's solution to resolve issues in Angular unit tests

Depending on how you use A-Frame in your app, this may or may not be an issue for you. However, as soon your test expects AFRAME or THREE to be defined in the DOM or in window, then importing A-Frame in the <head> of index.html can break and stop your unit tests from running.

This error can be reproduced by creating a basic script file that calls AFRAME. You might want to create your own A-Frame component and import them into Angular component:

// foo.script.js
AFRAME.registerComponent('foo', {
  schema: {},
  init: function () {},
  update: function () {},
  tick: function () {},
  remove: function () {},
  pause: function () {},
  play: function () {}
});

foo.script.js is imported into an Angular component to be used:

// foo.component.ts
import 'src/script/foo.script.js';

The application will run normally under ng serve. This is because index.html includes A-Frame.

// index.html
<head>
  <meta charset="utf-8">
  <title>Aframe</title>
  ...
  <script src="../node_modules/aframe/dist/aframe-master.js"></script>
</head>

You'll see the expected console.log where A-Frame correctly initiates:

A-Frame Version: 0.9.2 (Date 2019-05-06, Commit #f57a1fa)

three Version (https://github.com/supermedium/three.js): ^0.102.2

WebVR Polyfill Version: ^0.10.10

However, when we run ng t you'll note that this same prompt is missing in the console. A-Frame is not included here. Karma does not include A-Frame when it executes the unit tests. Karma will instead break, and your tests will not fully run.

./src/scripts/foo.script.js?:3 Uncaught ReferenceError: AFRAME is not defined

The .html file for the karma is located under:

node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\karma-context.html node_modules\@angular-devkit\build-angular\src\angular-cli-files\plugins\karma-debug.html

Once the import for A-Frame is included here (karma-context.html), then your unit test will include A-Frame and will run normally:

// karma-context.html
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <script src="https://aframe.io/releases/1.0.1/aframe.min.js"></script>
</head>

We can automate this for future tests by creating your own karma-context.html and karma-debug.html. Under scripts directory, create a copy each for both html files that includes the A-Frame import. Keep the karma-context.html and karma-debug.html unmodified in your node_modules folder. Changes inside are not propagated when your project is cloned, so our modifications need to live elsewhere.

Create a script that will copy the modified html into node_module when karma runs:

// scripts/karma-copy.test.js
const fs = require('fs');

// Modify karma-context.html
fs.copyFile(
  'src/scripts/karma-context.html',
  'node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/karma-context.html',
  (err) => {
    if (err) throw err;
  }
);

// Modify karma-debug.html
fs.copyFile(
  'src/scripts/karma-debug.html',
  'node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/karma-debug.html',
  (err) => {
    if (err) throw err;
  }
);

Include the script in karma.config.js:

plugins: [
  require('../src/scripts/karma-copy.test.js'),
  ...
],

Now, when you close your project, ng t will include A-Frame in the <head>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.