Home > Enterprise >  Problem Importing a JS Function in my Typescript Project
Problem Importing a JS Function in my Typescript Project

Time:05-01

I am making a project using ThreeJS and trying to import a js function that adds a ASCII Effect to the renderer but no matter how I do it I seem to get errors. I've tried several syntaxes and changing the TS config but no luck.

Edit: Just realised I should clarify, I downloaded the AsciiEffect function as a js file from the github repo directly so I am trying to import a single function from the file I downloaded "AsciiEffect.js" to my main TS file "main.ts". I am not importing from the ThreeJS dependency, as it is not a part of the package itself apparently.

TS Config File

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "commonJS",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true,
    "allowJs": true
  },
  "include": ["src"]
}

currently I am trying to import like this

import './style.css'
import * as THREE from 'three';
import {AsciiEffect} from './effects/AsciiEffect.js'

and exporting from AsciiEffect.js like this

export {AsciiEffect}

which gives me this error in the browser Uncaught SyntaxError: Export 'AsciiEffect' is not defined in module

I have tried using other syntaxes but had no luck, this is my first project attempting to use typescript and I actually expected the effect to be inside the ThreeJS dependency. I tried redoing what I have so far in JS but get the same error. The project was created using Vite if that helps at all. Its just a default TS project with no framework.

CodePudding user response:

You have a bad export, export the function like this: export AsciiEffect Then TS compiler will complain that it doesn't recognize that module, since it's a .js module and not a TS one, so you need to add custom moudle declaration:

  1. If you don't already have a *.d.ts file in the root of your project, create a file called declarations.d.ts.
  2. Inside of it add this line: declare module "path/to/the/module";

This way you are telling TS that that is a legit module to import from.

  • Related