Build several javascript files into one (require.js or something else) - javascript

My javascript project looks like this (Example A)
;(function (window, document, undefined) {
var func1 = function () {
// some code
};
var func2 = function () {
// some code
};
// ... some more functions
// lines of main code
// ...
})(window, document);
I want to place func1, func2, ..., code in separate files to make code like this (Example B):
;(function (window, document, undefined) {
var func1 = require ("func1.js");
var func2 = require ("func2.js");
// ... more requires
// lines of main code
// ...
})(window, document);
…and then somehow compile it to get the code as in Example A
Is there any particular way to do this? I tried to use require.js (r.js), but i've got require and define statements in compiled code (so I need require.js to run compiled code in browser). Is it possible to get flat static js-file without any dependencies with r.js? Maybe there is another way to do this? Thanx

Depending on how your code works, you can always just go cat *.js > all.js then run a minifier or something on it.

Related

Can see function from javascript file but not variables

My directory structure is as follows:
src
|--> js
|--> more js files in nested folders
test
|--> spec
|--> js test files
If within one of my js tests in spec, if I try and call a function from a js file within my nested src directories, I can call the function fine. However, if I try and call a variable, it cannot find it, and I get a Reference Error.
My function (which is visible) is declared like so:
function myFunctionName() {
... some code ...
}
My variable is declared after the function, and not inside any other function, like so:
var myVar = '...';
I've also tried declaring myVar as a const, for the same result.
In myTestSpec.js
(function () {
'use strict';
describe('...', function() {
it('...', function () {
// Works
expect(myFunctionName()).toEqual('...');
// Doesn't work
var newVar = myVar;
});
});
})();
Ended up solving this by just sticking any 'global' state I required into a function, to be returned as json. I now just need to call this function everytime I start a test.
This has a slight performance hit I guess as we need to recreate the state across multiple tests, however it's not production code (test only) so shouldn't be an issue, and it means I don't have to depend on another JS library such as require js..

Does Node run all the code inside required modules?

Are node modules run when they are required?
For example: You have a file foo.js that contains some code and some exports.
When I import the file by running the following code
var foo = require(./foo.js);
is all the code inside the file foo.js run and only exported after that?
Much like in a browser's <script>, as soon as you require a module the code is parsed and executed.
However, depending on how the module's code is structured, there may be no function calls.
For example:
// my-module-1.js
// This one only defines a function.
// Nothing happens until you call it.
function doSomething () {
// body
}
module.exports = doSomething;
// my-module-2.js
// This one will actually call the anonymous
// function as soon as you `require` it.
(function () {
// body
})();
Some examples..
'use strict';
var a = 2 * 4; //this is executed when require called
console.log('required'); //so is this..
function doSomething() {}; //this is just parsed
module.exports = doSomething; //this is placed on the exports, but still not executed..
Only in the sense that any other JS code is run when loaded.
e.g. a function definition in the main body of the module will be run and create a function, but that function won't be called until some other code actually calls it.
Before exporting the content that are visible outside of your module, if there is same code that can be execute it it execute but the content that are export like a class will be execute in the code that import it.
For example, if I have this code
console.log("foo.js")
module.exports = {
Person: function(){}
}
the console.log will be execute when you require it.

How to pack my library in a self executing function? (emscripten)

I've created a library in C++ using Embind and Emscripten.
Some hand written JS code is also added to the library using --pre-js
The library works. But I would like to rearrange the code, to this:
var MYLIB = (function(){
// ... Original Code ...
return Module;
})();
So the code would not pollute the global namespace, and the code minifier could do better optimizations.
Are there build in functions for this in emcc ?
The library will only run in webbrowsers, not in nodejs.
What you're looking for are the MODULARIZE and EXPORT_NAME options. Check the documentation in settings.js.
Quoting from that file:
// By default we emit all code in a straightforward way into the output
// .js file. That means that if you load that in a script tag in a web
// page, it will use the global scope. With MODULARIZE set, we will instead emit
//
// var EXPORT_NAME = function(Module) {
// Module = Module || {};
// // .. all the emitted code from emscripten ..
// return Module;
// };
//
// where EXPORT_NAME is from the option of the same name

External JS not defined

I've got a main JS script which looks something like this..
;(function ($) {
<main javascript>
}(jQuery));
I've just created my own external library script which looks like this..
;(function ($) {
var myClass = function() {
<code>
};
}(jQuery));
What I want to do is pass my external library into the main JS script, to look something like this:
;(function ($, myClass) {
<main javascript>
}(jQuery, myClass));
However it says that myClass is undefined. How do I go about defining it?
(In terms of how I'm inserting the code it's using register/enqueue script with Wordpress. Both files are "active" so if I was to throw an alert into them both then they'd both get fired off, I'm just struggling with linking the two together so that I can use the scripts inside myClass whilst within my main JS file).
Thanks
myClass is defined within the scope of
(function ($) {
...
}(jQuery));
so unless the code in that library does
this.myClass = myClass;
or something else to explicitly export it into the global scope then there is no way to reference it from your main script.
How do I declare a namespace in JavaScript? has a lot of discussion on the pros & cons of various ways of exposing an interface to other code in JavaScript.

different ways to parse and build with Grunt

In my project, i use an external library that it has some private functions on its local scope, it seems like this:
(function(window, undefined) {
var isArray = function() {...}
var forEach = function() {...}
var int = function() {...}
{(this))
The external lib gives me some funcionality, but additionally i will use these functions i mentioned in my project, so, I need to put externalLib private functions on window scope. To avoid that, i'm going to build myLib.js with my code and the externalLib code.
So, i need to put some code from externalLib.js (basically i only need to remove first and last line from the code).
What do you think about the best form to accomplish this task in GruntJS? I hope I explained well
You can preprocess files during grunt.js build using grunt-preprocess module. This requires some additional directives in your code:
// #ifdef DEBUG
(function(window, undefined) {
// #endif
var isArray = function() {...}
var forEach = function() {...}
var int = function() {...}
// #ifdef DEBUG
{(this))
// #endif
Where DEBUG can be any environment variable added either via command line switch or configuration file.
Also you can use #exclude directive that will simply remove code from grunt.js processed files. More on this here - https://github.com/onehealth/preprocess#directive-syntax

Categories

Resources