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.