I've been working on a website that requires a large amount of Javascript. Naturally, I have a number of classes and functions within my .js file. Is there any way, for the purpose of readability, to allow classes to be shared across multiple js files in the same directory?
Asked
Active
Viewed 479 times
-2
-
5If I'm understanding correctly, you're looking for [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export). – Tyler Roper Jan 28 '20 at 20:48
-
Does this answer your question? [Is it possible to give javascript partial class behavior like C# or monkey patching like Ruby does?](https://stackoverflow.com/questions/5998944/is-it-possible-to-give-javascript-partial-class-behavior-like-c-sharp-or-monkey) – Marcelo Gondim Jan 28 '20 at 20:51
-
@MarceloGondim I don't see that as a duplicate. This question doesn't really have anything to do with partial classes. – Tyler Roper Jan 28 '20 at 20:51
-
@TylerRoper its the same behavior. in c# is called partial class... so we can share class across multiple files – Marcelo Gondim Jan 28 '20 at 20:54
-
1@MarceloGondim I suppose OP could be asking about extending classes across multiple files, but as I understood it, it sounds like they just want to be able to define a function `MyFunction` or a class `MyClass` in `file_a.js` and use it in `file_b.js`. The question could fall into either the "duplicate" or the "needs clarity" bucket as it stands :) – Tyler Roper Jan 28 '20 at 20:56
1 Answers
3
Yes you can use multiple files with the export
and import
commands
To make classes in a file accessible outside it, export
the values:
// numberedClasses.js
class Class1 {
constructor() {
// Your code for the class here
}
// Your additional methods
}
class Class2 {
constructor() {
// Your code for the class here
}
// Your additional methods
}
export {Class1, Class2}
Next, you can access these using relative paths from another file (in this case I assume they are in the same directory)
// usingClasses.js
import {Class1, Class2} from './numberedClasses.js';
let itemC1 = new Class1();
let itemC2 = new Class2()

davidgamero
- 466
- 2
- 5