0

I'm kind of going nuts here.

I need to start writing a stand alone non web application in JavaScript.

My problem is that I can run (using nodejs) the script just fine, but I can't split the code that I need to write among multiple files because then I don't know how to include them.

Rigth now all I want is the simplest working example of including a JS file inside another so I can use the functions defined there (or class if I so choose).

My test.js looks like this.

const { outputText } = require("./text_module.node.js");
outputText();

While my text_module.node.js looks like this:

function outputText(){
   console.log("hello world");
}

My package.json looks like this:

{
  "type": "text_module.node.js"
}

I have tried

  1. Adding export before the function. It tells me export is unexpected
  2. Using this notation: import { something } from "a_path". Anything that uses this notation will get me an "Unexpected token {" error.

The current configuration simply tells me that outputText() is not a function. So I'm out of ideas.

I don't know how else to search. I've been searching for hours on this topic and it seem that no matter where I look there is some HTML code that is needed to tie everything togeter or using another third party tool. Using jQuery loads stuff "asynchronically" which is not what I need. I want it to sequential.

Is JS just NOT suppossed to be used like other scripting languages? Otherwise I can't figure out why this is so complicated. I feel like I'm missing something big here.

aarelovich
  • 5,140
  • 11
  • 55
  • 106

1 Answers1

1

If you want to use const { outputText } = require("./text_module.node.js");,

export it as module.exports = { outputText: outputText }.

In your question,

Adding export before the function. It tells me export is unexpected

Because it's an es6 thing and nodejs doesn't support all es6 features. You can refer to this answer for more details on that.

Sagar V
  • 12,158
  • 7
  • 41
  • 68