How about incorporating webpack, three.js demos, and typescript all together in one project?

I'm encountering difficulties when trying to integrate certain elements from threejs's examples, such as EffectComposer or Detector, with webpack and typescript.

Although the necessary *.d.ts files are installed using tsd, I am struggling to make webpack include files from the threejs examples/js/ directory.

When using three installed via npm, I am able to import THREE with:

import THREE = require('three');

This method works well, but does not provide access to the additional features I require. While there are other threejs packages on npm that bundle plugins, they seem incompatible with typescript (for example, require('three-js')(['EffectComposer']) causes issues with the typescript compiler).

Has anyone been successful in making elements from this package (such as postprocessing) work with typescript?

Answer №1

I have discovered a neat solution for configuring this in the webpack.config.js file.

Following Dan's advice:

$ npm install --save-dev imports-loader

It appears that we do not actually require exports-loader, as the constructors are added to the THREE object in the three.js examples.

Therefore, within the webpack.config.js file, we can implement a rule to include var THREE = require('three'); in an imported module whenever the module's path contains three/examples/js:

module: {
  rules: [
    ...
    {
      test: /three\/examples\/js/,
      use: 'imports-loader?THREE=three'
    }
  ]
}

Now the example modules will recognize the global THREE object as expected.

To simplify the import process for examples:

resolve: {
  alias: {
    'three-examples': path.join(__dirname, './node_modules/three/examples/js')
  },
  ...
},

Assuming that the webpack.config.js file is located in the same directory as node_modules, make adjustments if necessary.

Now, we can utilize the example files like this:

import * as THREE from 'three';
import 'three-examples/controls/OrbitControls';

for importing the module for its side effects.

If you encounter warnings about the example module not being found on THREE when using Typescript and/or Babel, you might find this issue on the imports-loader repository helpful as a reference.

Answer №2

Here is the solution that successfully resolved my issue.

$ npm install --save-dev exports-loader imports-loader

After installing the necessary loaders, I implemented the following code to utilize functionality from three/examples/js:

const THREE = require('three');
// The imports loader provides THREE to the OrbitControls example
// The exports loader obtains THREE.OrbitControls
THREE.OrbitControls = require('imports?THREE=three!exports?THREE.OrbitControls!../../node_modules\/three\/examples\/js\/controls\/OrbitControls');

// Now, I can utilize THREE.OrbitControls ...

It is advisable to utilize the imports and exports loaders according to the configuration guidelines provided by webpack, instead of embedding them within the require statement. I will update this response with a practical example soon.

Answer №3

I successfully integrated OrbitControls into my project using webpack v2 and ts-loader without the need for any additional loaders.

Here is a snippet from my package.json file:

"dependencies": {
    "three": "^0.85.2",
    "@types/three": "^0.84.12",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1"
},

Within my entrypoint.ts file, I imported THREE from "three" and made it available globally:

import * as THREE from "three";

// OrbitControls.js requires a global THREE object
(window as any).THREE = THREE;

// NOTE: Make sure to require OrbitControls, do not import as it may execute before global THREE is available
require("three/examples/js/controls/OrbitControls");

// ... code that utilizes THREE and THREE.OrbitControls

It's worth noting that webpack may display a warning like

"export 'OrbitControls' (imported as 'THREE') was not found in 'three'
, due to OrbitControls.js not being a proper JS module. This warning can typically be disregarded.

Answer №4

Regarding the integration of TypeScript and ThreeJS within your IDE, I will focus on that part of your question.

Most components can be found on the DefinitelyTyped archives. It is recommended to switch from using tsd to typing.

Below is a sample typings.json file that can be consumed by typing. It includes the latest main ThreeJS and the effect composer library for TypeScript recognition. Keep in mind that the commit hashtags may change as the .tsd version evolves.

{
  "ambientDependencies": {
    "three": "github:DefinitelyTyped/DefinitelyTyped/threejs/three.d.ts#c6c3d3e65dd2d7035428f9c7b371ec911ff28542",
    "three-projector": "github:DefinitelyTyped/DefinitelyTyped/threejs/three-projector.d.ts#48f20e97bfaf70fc1a9537b38aed98e9749be0ae",
    "three-detector": "github:DefinitelyTyped/DefinitelyTyped/threejs/three-effectcomposer.d.ts#48f20e97bfaf70fc1a9537b38aed98e9749be0ae",
    "three-effectscomposer": "github:DefinitelyTyped/DefinitelyTyped/threejs/detector.d.ts#48f20e97bfaf70fc1a9537b38aed98e9749be0ae",
    "three-shaderpass": "github:DefinitelyTyped/DefinitelyTyped/threejs/three-shaderpass.d.ts#ee05b1163d8da7f16719f08d52f70ab524f1003a"
  }
}

An image is provided showing an IDE recognizing the public methods of the EffectsComposer. You can also explore different module loader capabilities of TypeScript.

https://i.sstatic.net/a7uPL.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The vertexUv in three.js is currently undefined and needs to be

I'm currently facing an issue while trying to combine multiple meshes, one of which is created by inputting the vertices coordinates. This specific mesh is causing the following error: THREE.DirectGeometry.fromGeometry(): Undefined vertexUv 256 W ...

What is the best way to confirm that a certain element is not present on the page using playwright?

My current challenge involves testing a website that features a logo, and I need to ensure that the logo does not display on specific pages. I have been exploring the Playwright assertions documentation for guidance on how to assert that an element does N ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

The GLTF 3D model failed to animate as expected

My current objective is to create an animation for a 3D model that I have imported as a .gltf file. The model contains only one animation. After carefully following the steps outlined in the documentation: And exploring various examples on the internet, ...

Guide on utilizing Three.js OrbitControl with several objects

I managed to get the orbit control feature working, but I am facing an issue where controlling one object also ends up controlling all three objects on the page. Additionally, pan/zoom functionality does not seem to work at all with the OrthographicCamera. ...

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

Using Tween animations with Three.js

I have some queries regarding tween js within three.js. Below is the code snippet where the particles are generated as shown in the image: Image 1 // Code snippet for initializing var scene; var renderer; var container; var stats; var sphere; // Omitted ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Is there a way to retrieve a compilation of custom directives that have been implemented on the Vue 3 component?

Is there a way to retrieve the list of custom directives applied to a component? When using the getCurrentInstance method, the directives property is null for the current component. I was expecting to see 'highlight' listed. How can I access the ...

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...

Is it possible to have an interface, function, and variable all sharing the same name in a declaration?

Is it possible to have an interface, function, and variable all with the same name? For example, I would like to define the function as follows: declare function someName(...args: any[]); someName('foo'); The interface would look like this: ...

Incorrect form of SphereGeometry detected in three.js

I'm having trouble rendering a simple sphere in three.js because it's appearing distorted (looking more like a vertical stick). Below is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

TypeScript Library encounters issues when importing a specific data type

I recently integrated a library into my Next.js application to manage layouts using useState in react-grid-layout. To make this work with TypeScript, I had to install the necessary package shown below: npm install --save @types/react-grid-layout The code ...

Combining various outcomes into a single entity for ion-slide in Ionic 2

I am facing a similar issue with this problem, but with a different twist. I want to showcase three results in ion-slide, and while iDangero Swipper seems like a solution, I believe ion-slide could also achieve something similar to this. Please take a look ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I hav ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase. The current status in the Filter is as follows: Name 1: Lea Muster Name 2: Bruno Mustermann Name 3: Lea Muster Name 4: Gabriela Musterfrau The goal is to show duplicate e ...