0

I'm using parcel, and I'm trying to use ES6 import and export syntax. Parcel seems to run babel underground, I'm very new to it. When openimn the index.html placed on "dist" folder it does not render well and shows this error in console: "Uncaught TypeError: (0 , _module.importedHi) is not a function"

This the code in the exporting JS file:

export const importedHi = document.write("Hello world")

And this is the code of the main.js:

import {importedHi} from "./module1";

importedHi()

And this is the script im using in index.html

<script src="js/main.js"></script>

What do I have to configure so that this works properly?

Leftium
  • 16,497
  • 6
  • 64
  • 99
Julio Rodríguez
  • 447
  • 1
  • 8
  • 23

1 Answers1

2

document.write returns undefined, so importedHi is undefined, and importedHi() throws an error. You probably wanted to export a function that calls document.write, eg:

export const importedHi = () => document.write("Hello world");

Still, if you're at the point that you can use modules and bundlers, you should probably use more modern methods of manipulating the DOM, like createElement / appendChild and such, perhaps something like

export const importedHi = () => {
  document.body.appendChild(document.createTextNode('Hello world'));
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • `You probably wanted to export a function that calls document.write` to be fair, nobody wants to export a function that calls `document.write` :p – Jaromanda X Apr 26 '19 at 03:16
  • Well, for learning porpuses it is valid, dont you think? Or do you want me to build the new facebook app in order to learn? – Julio Rodríguez Apr 26 '19 at 03:20
  • You *can* use `document.write` if you want, it's just not a good idea - many linters warn against it, it can be a form of `eval`, and it will unintuitively replace the current document if the document has already loaded. There's no use learning it IMO - it shouldn't be used, use other DOM methods like the ones I mentioned or `insertAdjacentHTML`. (Similarly, there are many cases where you *can* use `eval`, but it's ugly and can be unsafe, so generally you shouldn't, if you can avoid it) – CertainPerformance Apr 26 '19 at 03:25
  • I fixed it as @CertainPerformance recommended, however, I still get the same error.. I'm having serious problems implementing import / export :( – Julio Rodríguez Apr 26 '19 at 03:53
  • 1
    @JulioRodríguez I can't reproduce, it appears to be working as desired for me https://codesandbox.io/s/72v4pjk07q – CertainPerformance Apr 26 '19 at 04:06