在Angular 8中,如果使用Webpack来加载THREE.js,可能会出现THREE.js加载两次的问题。以下是解决这个问题的代码示例:
首先,在你的Angular项目中安装THREE.js和@types/three:
npm install three @types/three --save
然后,在你的Angular项目的webpack.config.js文件中添加以下代码:
const webpack = require('webpack');
module.exports = {
// ...
plugins: [
new webpack.ProvidePlugin({
'THREE': 'three'
})
]
};
接下来,在你的Angular组件中,你可以使用THREE.js了。例如,在app.component.ts中:
import { Component, OnInit } from '@angular/core';
declare var THREE: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
// 使用THREE.js来创建一个场景
const scene = new THREE.Scene();
// ...
}
}
现在,你的Angular项目中的THREE.js只会加载一次了。