简体   繁体   中英

How to import a JavaScript method from another JavaScript file in eclipse

I'm on a Dynamic Web project development, and I have properly organized my JavaScript files in the JavaScript folder, the thing is that I have more than one methods that I have to copy-paste from one.js to another. In order to avoid that duplicity I want to have a.js where all this popular methods are defined so I just have to import them in any.js I need.

I have no clue about how to do that on Eclipse IDE, hope someone can guide me.

It is really helpful to separate projects out into different files to allow for less duplicate code.

I am going to make a strong assumption here saying that you are using CommonJS require to import libraries. CommonJS or CJS imports often look like this;

const package = require('package-name);

When you want to allow a function to be exported from a file you will create your own module and export it for use. Let's say you have a file named car.js which contains a bunch of information to return about the car; I have a function named getNumberOfTires() and I want to use it in my main javascript file, index.js . I am going to add a line to the end of car.js to export a single function or in my example just getNumberOfTires() . The line looks like this

exports.getNumberOfTires = getNumberOfTires;

This looks a lot like assigning a property of an object with normal JavaScript which is what we are doing of sorts. We are assigning that this file has an export named getNumberOfTires which is assigned to the function.

To import this into the main file we do much like what I defined above in the CJS example.

const car = require('./car.js');

car.getNumberOfTires();

This imports the file as the variable car then we can call getNumberOfTires() off of that variable.

However; when you want to start exporting multiple functions out of a single file we can do the same thing. We can continue our same semantics as above and label each export.

We will use the same semantics as if we were importing just a single function. There are plenty of different ways to import and export functions. These are just a couple of examples.

Sources used: https://www.sitepoint.com/understanding-module-exports-exports-node-js/

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