How can I disable JS functions from the global namespace?

I am writing a third-party JS application using requireJS, and I want the global namespace to be clean from everything except the only global interface object that my application will create. I had no problems with this except requireJS.

As an option for the optimizer, require.js can be inserted into the assembly, and the namespace can be defined to make the optimizer scope all references to the required functions for this namespace.

eg. require (...) becomes my_scope.require (...)

The problem is that this global namespace object will not exist until it is created in the application. The optimizer ensures that requireJS is loaded and executed before any of the code that it loads, so when it comes time to execute the require function (for example, require or define), an exception is thrown (namespace object is undefined).

Has anyone successfully done this without manually changing the built-in script or by running another script separate and before the built-in script? In other words, is there a suitable way to achieve this?

+4
source share
2 answers

For everyone who was looking for the answer to this question, here it is, found in a heap of used elbow grease.

In the build configuration settings, forget about using namespace . There is a β€œwrap” property that allows you to wrap the entire script construct in the code of your choice.

Just define it as the following to create a local area around everything (including requireJS functions):

 require.config({ wrap: { start: "(function() {", end: "}());" } }) 
+5
source

I believe that requirejs and module loaders generally have a different approach to reducing global clutter than the namespace. If necessary, you do not need to bind things to the global namespace, just use the call to the require method within the closure to get local references.

So you are exchanging one bit of global clutter (i.e. window.require) for all the other things you will need to attach.

In an implementation with a name extension, you should use something like

 var foo = window.my_scope.foo.bar 

With module loaders you should use a call. In the case of the CommonJS module loader, you would do something like this

 var foo = require("my_scope/foo/bar") 

RequireJs adds a bit more complexity because it is an AMD module loader, but this other whole conversation is in itself!

0
source

Source: https://habr.com/ru/post/1387524/


All Articles