简体   繁体   中英

Issue exporting function from typescript file

I have this .ts file:

let animalTypes: string[] = ["MOOSE","COW","HORSE"];

function getNoise(animalTypes) {

    if (animalTypes === "MOOSE") {console.log("NEIIIIIIIGH whatever noise Moose make");}
    else if (animalTypes === "COW") {console.log("MOOOOOOOOOOO");}
    else if (animalTypes === "HORSE") {console.log("WHINNNNY");}

}

export {getNoise}

Which transpiles into this .js file:

"use strict";
exports.__esModule = true;
var animalTypes = ["MOOSE", "COW", "HORSE"];
exports.animalTypes = animalTypes;
function getNoise(animalTypes) {
    if (animalTypes === "MOOSE") {
        console.log("NEIIIIIIIGH whatever noise Moose make");
    }
    else if (animalTypes === "COW") {
        console.log("MOOOOOOOOOOO");
    }
    else if (animalTypes === "HORSE") {
        console.log("WHINNNNY");
    }
}
exports.getNoise = getNoise;

However, I'm receiving this error message when trying to load the .js file and import the functions directly into a block on my website:

Uncaught SyntaxError: The requested module './animals.js' does not provide an export named 'getNoise'

I'm copying an example from class so it's bewildering that it isn't working but there we have it.

Does anyone know what might be causing this SyntaxError?

Here is the relevant html, too:

import {getNoise, animalTypes} from "./animals.js";
document.getElementById("target").onclick = function() {
      getNoise(animalTypes[1]);
}

It looks like you are loading modules into the HTML file using the ECMA6 module loader and compiling your TypeScript into CommonJS modules.

Those two module systems are not compatible.

Try changing your tsconfig.json file so that it builds ECMA6 modules instead.

{
  "compilerOptions": {
    "module": "es2015",
  },
}

Your HTML file would then look like this:

<script type="module">
    import { getNoise, animalTypes } from "./animals.js";
    const noise = getNoise(animalTypes[1]);
    console.log(noise);
</script>

Here is a demo for your on GitHub. Note also that you need to export animalTypes in addition to getNoise like this:

export {
  animalTypes,
  getNoise
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM