5 thoughts on “es6 import three.js

  1. You’re excluding node_modules in babel-loader (so three.modules.js never goes through Babel), and only Webpack 2 supports ES Modules natively, so you need to change either one of those conditions.


    Here’s a working example for Webpack 2.

    application.js:

    import {Scene, PerspectiveCamera, WebGLRenderer, BoxGeometry, MeshBasicMaterial, Mesh} from 'three';
    
    const scene = new Scene();
    const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    
    const renderer = new WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    
    const geometry = new BoxGeometry(1, 1, 1);
    const material = new MeshBasicMaterial({color: 0x00ff00});
    const cube = new Mesh(geometry, material);
    scene.add(cube);
    
    camera.position.z = 5;
    
    function render(){
    	requestAnimationFrame(render);
    	cube.rotation.x += 0.1;
    	cube.rotation.y += 0.1;
    	renderer.render(scene, camera);
    }
    
    render();

    webpack.config.js:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    
    module.exports = {
    	target: 'web',
    	devtool: 'source-map',
    	entry: './src/application.js',
    	output: {
    		path: path.resolve(__dirname, 'www'),
    		filename: 'bundle.js',
    		publicPath: ''
    	},
    	plugins: [
    		new HtmlWebpackPlugin({
    			title: 'Example',
    			filename: 'index.html'
    		})
    	],
    	module: {
    		rules: [
    			{
    				test: /\.js$/,
    				include: [
    					path.resolve(__dirname, 'src')
    				],
    				loader: 'babel-loader',
    				query: {
    					compact: true,
    					presets: [
    						['es2015', {modules: false}]
    					]
    				}
    			}
    		]
    	}
    };
  2. @v1talM

    import { Math } from 'three/build/three.modules'
    
    Math.degToRad();
    

    Keep in mind, there’ll be collisions with browser’s Math object, so make sure you prefix them with window. window.Math.sqrt(...)

    Btw, for quick and dirty drop in module testing, you can do this too:

    import * as THREE from 'three/build/three.modules';
    
    new THREE.Mesh....
    
  3. import {Math as ThreeMath} from 'three/build/three.modules' should also work to avoid name clashes.

Comments are closed.