Packing multiple JavaScript libraries with distinct namespaces and classes in separate files

I am dealing with various files containing namespaces and classes structured as follows:

1) namespace.js:

var mynamespace = window.mynamespace || {};

2) class1.js:

mynamespace.class1= (function() {
  var _public = {};
  _public.someBoolean= false;
  return _public;
})();

3) class2.js:

mynamespace.class2= (function() {
  var _public = {};
  _public.init= function() {
  };
  return _public;
})();

My goal is to bundle them together and make them accessible through a library. The structure I have in mind is something like the following:

expose default {
  mynamespace
};

This way, I can use it in a different project by importing it as shown below:

import * as mynamespace from 'mynamespace';

var a = function() {
    mynamespace.class1.someBoolean = true;
    ansomenamespace.class2.init();
};

Can you guide me on how to achieve this? Also, I would like to expose its type definitions for TypeScript usage. Thank you!

Answer №1

You seem to be mixing the import/export style modules with those attached to window. It's advisable to choose one approach and stick with it.


For instance, if you want to attach everything to window:

namespace.js

var somenamespace = window.somenamespace || {}; // not required

class1.js

var somenamespace = window.somenamespace || {};

somenamespace.class1= (function() {
  var _public = {};
  _public.someBoolean= false;
  return _public;
})();

class2.js

var somenamespace = window.somenamespace || {};

somenamespace.class2= (function() {
  var _public = {};
  _public.init= function() {
  };
  return _public;
})();

using the module

// simply access from window without importing

var a = function() {
    window.somenamespace.class1.someBoolean = true;
    window.ansomenamespace.class2.init();
};

Alternatively, I suggest using import/export, but remember to transpile your code with Babel or Webpack since not all browsers support ES modules:

namespace.js

export {class1} from './class1'
export {class2} from './class2'

class1.js

export const class1 = (function() {
  var _public = {};
  _public.someBoolean= false;
  return _public;
})();

class2.js

export const class2 = (function() {
  var _public = {};
  _public.init= function() {
  };
  return _public;
})();

using the module

import * as somenamespace from './namespace'

var a = function() {
    somenamespace.class1.someBoolean = true;
    ansomenamespace.class2.init();
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide on defining a property within the ng-repeat's scope

My goal is to create a dynamic list of items that can be edited individually. Each item should have its own editing mode. Here's the code I'm using: <ul ng-controller="ItemCtrl"> <li ng-repeat="item in items"> <div cl ...

Tips for effectively handling notifications using a single state management system

This React project showcases the Notification System demo provided by Mantine. It includes several function components utilizing notification. const A = () => { useEffect(() => { notifications.show({ // config }); }, []); retur ...

Inactive drop-down menu

I'm a beginner at javascript and still trying to grasp the concept. My attempt at creating a dropdown bar involved using HTML with a nav bar containing a div with anchor tags. The javascript function I wrote uses querySelectorAll to retrieve the ancho ...

The nodes.attr() function is invalid within the D3 Force Layout Tick Fn

I'm currently experimenting with the D3 Force Layout, and I've hit a roadblock when it comes to adding elements and restarting the calculation. Every time I try, I keep encountering this error: Uncaught TypeError: network.nodes.attr is not a fun ...

Express.js is unable to redirect to a customized URL scheme

I'm currently having an issue with redirecting users to a custom URL scheme using Express.js in order to launch an app on my iPad (using "example://"). Below is the code I have written to handle the redirection from a button press on a page hosted on ...

Need a module from the main directory

Imagine having these folders: 'C:\\src' // Main directory. 'C:\\src\\inner1' // Contains 'a.js' 'C:\\src\\inner2\\innermost' // Contains 'b.js' ...

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...

How to Fetch a Singular Value from a Service in Angular 4 Using a Defined Pattern

I am currently working on developing a service in Angular 4 (supported by a C# RESTful API) that will facilitate the storage and retrieval of web-application wide settings. Essentially, it's like a system for key-value pair lookups for all common appl ...

Arrangement of bootstrap and CSS library in header has an impact on the styling of h3 Tag

After rearranging the order of the online Bootstrap and offline CSS library, I noticed an impact on the h3 element in my HTML document. To further clarify this conflict, let me provide more details. <link rel="stylesheet" href="https://maxcdn.boot ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

What is preventing me from accessing the sub-elements of an AngularJS controller?

I know this question has probably been asked countless times before, but I'm struggling to find the right words to explain my specific issue. Essentially, I'm having trouble accessing something like $ctrl.thing.subelement. However, the following ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

The decision between using multiple then statements or consolidating your code into a single then statement depends on the specific requirements

I am facing a situation where an api call returns data asynchronously and I have 2 methods that need to execute after the call is completed. However, these methods do not generate new promises on their own. Can const foo = new Promise(…); foo.then(() = ...

I'm looking for a way to transform multiple arrays into HTML tables in JavaScript and display them as I loop through a JSON object. Can anyone

In my for loop, I iterate over a JSON object and if it encounters an array, I generate an HTML table to display the information in a more structured and readable format. This is particularly helpful as arrays can contain a large amount of data. If no array ...

Unleashing the power of Javascript to generate all possible combinations of multiple arrays of objects

I am seeking to generate a comprehensive list of combinations from two arrays of objects. The JSON files I have are: Fruits [ { "food": "Apple", "calories": 100 } ], [ { "food": "Orange" ...

Tips for Providing a Generic Type to a Component Imported Using Next.js Dynamic

There is no issue with this code snippet: import DatasheetContainer from '@/uikit/detailed-view/DatasheetContainer'; const DetailedView = () => { return ( <Page> <PageBody direction="row" bgColor="white&qu ...

Learn the process of accessing web config values within Vue.js code

Just diving into the world of Vue and eager to learn. Question One - I'm interested in pulling values from webconfig into Vue, rather than hardcoding directly into the Vue file. Does anyone have any insight on how I can achieve this? Question Two - ...

Is it possible to prevent Firebase Auth Network Error by using event.preventDefault() and event.stopPropagation()?

Encountering an error while attempting to log in. The email address is present on Firebase Auth and login is successful, but the error occurs specifically when event.preventDefault() and event.stopPropagation() are used. These lines are marked with a comme ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

The SonarQube code coverage differs from that of Jest coverage

I'm struggling to grasp why SonarQube and Jest coverage results differ so significantly. SonarQube coverage resultshttps://i.sstatic.net/dodGi.png Jest coverage https://i.sstatic.net/uYKmt.png https://i.sstatic.net/rakzw.png https://i.sstatic.net/ ...