How to include/import an entire JS file with Webpack - javascript

I am new to Webpack, but I have a habit of building my web apps in the following manner:
Declare a global variable for the project.
Create several JS files that use the global variable to declare functions and variables
Link these separate js files in the HTML file, and combine them when going to production.
For example my first JS file would be "init.js":
let FP = {}; // Global Object
My second would be "processing.js":
FP.addNumbers = function(a, b){
return a+b;
}
The HTML would include:
<script src="init.js"></script>
<script src="processing.js"></script>
Then in production I use a node plugin I wrote to parse the HTML page and combine all the JS files into one.
I want to do something similar with Webpack, but the only way I found to combine files is with "include". Which requires each file use a separate variable name.
I literally just want to dump the contents of my separate JS files into init.js. Is there a way to do this?

If you're going to use Webpack to bundle your code, the right approach to something like this would be to take advantage of modular imports and exports to coordinate data between modules, otherwise the use of Webpack isn't really doing anything for you.
For example, here, try the following:
// index.js
import { addFns } from './addFns.js';
const FP = {};
window.FP = FP; // use this if the object needs to be global
addFns(FP);
// addFns.js
export const addFns = (FP) => {
FP.addNumbers = function(a, b){
return a+b;
}
};
Then, Webpack can create the complete bundle with only a single .js file as output automatically, and it'll be ready for production with any more post-processing.

Related

Use require only once

I have a javascript file including many files by the use of require. Some of them are helper files. While other are functions of nodes. I want those helper functions to be included anywhere.
module.exports = {
node1: require('node1.js'),
functions1: require('./functionsq.js'),
}
However, this way i cannot use function1 in node1. Is there a way to use functions1 in node1, while it must not be included in the node file again by require?
**var f=require('functions.js')**
var node1={
...
}

How to package object prototypes in separate file

I have created a number of String.prototype functions which for maintainability I'd like to have in its own file. That is, I'd like to include the file in a javascript project and thus have all the String functions defined.
I could create a module that exports each function, but then I'd have to assign each function as its own String prototype, yes? Something like
var myStringFunctions = require("myStringFunctions");
String.prototype.func1 = myStringFunctions.func1;
Is there a way to include such a file so that the prototypes are defined as part of the inclusion?
Try it, you will see your code and using require("./myStringFunctions"); works just fine.
./myStringFunctions.js
String.prototype.func1 = function() {
return this.toUpperCase(this);
};
./index.js
require("./myStringFunctions");
console.log("foo".func1()); // FOO
If your JS is going to run in the browser, you can use JS modules with the import and export syntax if you use a module bundling build tool like Webpack: https://webpack.js.org/ .
If your JS is running in a Node.js environment, modules are supported: https://www.w3schools.com/nodejs/nodejs_modules.asp

NodeJS - how can I make my code beautiful / cleaner / better readable

I have generated my app with express --view=pug myapp which created me a folder-tree with the files I need to start over.. I wrote some code which I would like to outsource from the main app.js in maybe a function-file or something like that, to keep the app.js cleaner.
where would I put my custom functions? how would I then require the function-file in nodeJS ?
You can arrange your files as you wish. Wherever you keep your functions, just add the functions you want to use in any other files to module.exports object in that file. Then in your app.js (or any other file where you want to use these functions), import the file using require and you should have access to all the exported properties and functions from the file you import.
For example:
I can put my functions in ./lib/core-lib.js:
function test(){
// do something
}
module.exports = {
test: test
};
And then in my app.js
const lib = require('./lib/core-lib');
lib.test();

Global variables are undefined for imported Javascript functions

Trying to figure out if there is a problem due to the import/export method, or if my architecture just bad....
Previously, I had multiple files of javascript. Just functions, no classes. In one "center/main" JS file, there are global variables. These variables are accessed and used/updated by functions in that same file, as well as other files. Each JS file had to have its own tag within the index.html
The move was then to switch to webpack as a module builder which would remove the need for all those script tags. Instead I just have to import/export the functions.
The problem is that now after using that method, the global variables are undefined to the imported functions Below is the setup dumbed down, but I don't see why it would be a problem. Maybe I'm missing something.
main JS file
import * as SettingsFile from './settings';
var myVariableUsed;
$(document).ready(function() {
myVariableUsed = "test";
SettingsFile.startSettings();
});
secondary JS file (settings.js)
export function startSettings(json) {
console.log(myVariableUsed);
}
Hy, i think you can understant what is happening with this article:
https://medium.com/webpack/brief-introduction-to-scope-hoisting-in-webpack-8435084c171f
To be short, webpack creates a new scope for required files, because of 'use strict' declaration on generated code output.
To pass parĂ¢meters to required modules you need to do do something like this:
// somefile
require("lib.js")(param1, param2)
// lib.js
module.exports = function(param1, param2) { }

Can you minify multiple files into one?

I have my JavaScript code split into few files, all using the module pattern (updating one global variable, say MyApp, with new features and members.
Will it be possible to minify the files into one and not spoiling the scopes
Example I want to minify:
File1.js
var Module = (function(ns) {
ns.fun1 = function() { alert('fun1'); };
return ns;
})(Module || {});
File2.js
var Module = (function(ns) {
ns.fun2 = function() { alert('fun2'); };
return ns;
})(Module || {});
The global scope is in fact global, in that it doesn't matter if you are changing it from one file or multiple files. However, the order of your files can matter, depending on the module pattern flavour you're using. For a good writeup, covering cross-file private state also, read this: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Yes you can, and is a good way to work, for everyone, especially if more developers are involved and healthy for the application.
I use the Minify class (http://code.google.com/p/minify/) with a special config file (https://beat.snipt.net/minify-config-file-minify-each-folder-from-project-1-minified-file/) that scans my folders and makes for each subfolder a file (JS or CSS).
This way I can make modular JS or CSS files, that can be splitted on classes or regular files.
The key is the ORDER of the files, depending on the read-folder functions and OS type may be different (ex php readdir vs scandir)

Categories