ES6 import syntax imports whole file instead of function only - javascript

I have a couple of JS files with quite a few functions. In one of the files, I have a function written that I wish to export and use in another file. Here is the function:
export default function updateMinimumAmountNotice(subtotal) {
let parsedSubtotal = parseFloat(subtotal);
let minimumOrderAmount = parseFloat(minimum_order_amount);
if (parsedSubtotal < minimumOrderAmount) {
minimumOrderNotice.find('#checkout-amount').text((minimumOrderAmount - parsedSubtotal).toFixed(2));
} else if (parsedSubtotal >= minimumOrderAmount) {
minimumOrderNotice.hide();
}
}
In my other file, I am importing it like so:
import updateMinimumAmountNotice from './single-product';
When I import the function updateMinimumAmountNotice, I get errors on the page that are from non-imported functions in the same file of the function that I am importing. None of those functions are exported and the file is not loaded on the page. Most of the JS files are page-specific and only load on the page they have logic for.
If it matters, I am using Webpack as a build tool with BrowserSync.
So, is this normal behavior for importing/exporting modules, or is there something else going on?

Related

Propper way to make a javascript library (with multiple files)

I want to make my own javascript library with some utils functions and classes for the client browser. The point its I only want to include the main file.
https://github.com/encarbassot/elioUtils.js
I've tried using the type module
having ./src/array.js, ./src/math.js, ./src/dom.js with some functions with export, thei i have two options
OPTION 1:
/lib/utils.js
import * as array from "./src/array.js"
import * as dom from "./src/dom.js"
import * as math from "./src/math.js"
export {array,dom,math}
but in the script i have to do:
script.js called from html
import {math} from "/lib/utils.js"
const {lerp} = math
the point of modules is to import only the functions you need and here i'am importing all math functions
OPTION 2:
import {zip,create2DArray} from "./src/array.js"
import {isTouchDevice,coptyToClipboard,scrollToCenter} from "./src/dom.js"
import {lerp,inverseLerp,map,clamp} from "./src/math.js"
export {zip,create2DArray,isTouchDevice,CopyToClipboard,lerp,inverseLerp,map,clamp}
but in this example every function i create in some ./src/ file i have to modify the utils.js file
also all libraries i use they dont use module, they are a big class or a big function
i thought about putting all inside a big object like
const utils = {}
utils.lerp = (start,end,amt)=>{
return (1-amt)*start+amt*end
}
// ... and more functions
or using multiple files and then compile them to the big file maybe ???
other option would be to do
document.write('<script src="/lib/src/math.js"></script>');
document.write('<script src="/lib/src/dom.js"></script>');
document.write('<script src="/lib/src/math.js"></script>');
but for what i think its not a very good practice
and last, jQuery you can import the file like a module and like a src file
and i'm trying to avoid things like webpack, i want to keep it vanila

Exporting one set of functions from multiple files

I've just finished writing a big quickbooks wrapper in JavaScript with a lot of parts in different files, e.g. a file for tax, a file for accounts, a file for auth, etc. I'd like to make it so that developers using this wrapper will only have to do one import that will contain all the functions I've written.
Hierarchy is something like this:
QbTax.js
QbAccounts.js
QbAuth.js
I'd like to have another file, or a way that a developer using this wrapper would only have to import one thing, then be able to call all functions from the above files from that one import.
Something like this:
import * as qb from './unifiedQbFile.js';
qb.thisIsATaxFunc();
qb.thisIsAnAccountsFunc();
qb.thisIsAnAuthFunc();
What is the best way to approach this?
The only idea I have at the moment is to write prototypes in a file (unifiedQbFile.js for instance) and export those. I'd import all the functions from my other files in that unified file then call them in my new prototypes. That seems messy though.
you can have one index.js file that exports all files then you can import that index.js file. I would personally go with this method.
// index.js
export { qbTaxFunc } from 'QBTax';
export { qbAccountsFunc } from 'QbAccounts';
export { qbAuthFunc } from 'QbAuth';
Now in some other script to import it you can do.
import qb from 'path-to-index.js';
// All functions should now be available
qb.qbTaxFunc();
qb.qbAccountsFunc();
qb.qbAuthFunc();

Webpack global variable from multiple files

I'm trying to rewrite bunch of legacy JS files into module structure. I have obfuscated plugin which contains out of few files, which in turn work with single global variable. The order of execution of these files matters.
Example:
file1.js
var myModule = {someStuff};
file2.js
myModule.someProperty = someValue;
What i want to achieve is to import them all somehow and get this global variable myModule.
Possible implementation:
myModule.js
import myModule from "file1.js";
import myModule from "file2.js"; // ofc i know it does not work this way
export default class myProgramm {
constructor(){
myModule.run({options});
}
}
What i tried so far is webpack provide plugin (https://webpack.js.org/plugins/provide-plugin/), but it doesn't work with multiple files. Also i tried to use provide-multiple-plugin (adopted to webpack 4) from this gist :https://gist.github.com/shellscape/a7461022503f019598be93a512a1901a. But it seems to include files in nearly random order, so it can happen that myModule is not defined, while file2.js is executed first.

How does the JavaScript Import work under the hood?

How does the import statement actually work in JavaScript? I read the documentation and it says that it places exported code within the scope of the file. Does that mean that the code is copied over into the file where I type import?
For example - in library.js I have:
export {export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
In main.js I have:
import { getUsefulContents} from 'library.js';
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
This allows me to call getUsefulContents() in main.js. My question is, does main.js now have the contents that I exported from library.js?
Is using import the same as just having physically defined getUsefulContents() in main.js?
function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
The main reason why I ask is because I want to know if using import will have an effect on main.js file size? Or is something else going on under the hood?
Thank you!
Depends on how you are using main.js. If you run it through a bundler, then the bundler will probably include library.js into main.js to pack it up into one file. In that case, the only advantage would be maintainability and ease of development because you are focused on the file you are working on. If you are simply running the import statement and deploying your application, the import statement won't affect the file size of main.js.
It just namespacing it within the file that you are importing it to so
any code from useful-library.js is included in the file, I visualize it this way
import { usefulCodeFromLibrary } from './useful-library.js';
((usefulCodeFromLibrary)=>{
// My excellent code
// Imported code doing it's job
usefulCodeFromLibrary.someHelperFunction()
}()

Webpack 2 accessible functions from different js files

Just started using webpack-2 and have a question about global functions. Have these functions in js file named showPictures.js:
function isEmpty(el) {
var result = !$.trim(el.html());
return result;
}
function showPicturesList() {
if (!isEmpty($('#picture-name-list'))) {
var pictureList = document.getElementById("added-pictures");
pictureList.style.visibility = 'visible';
}
}
And I have another file util.js in witch I am calling showPicturesList() function
window.onload = function(){
showPictureList();
}
Simply using js I would import both scripts into my html, but with webpack I can make one file for both of them so webpack.config.js I added both of these files as entry array.
My output file bundle.js looks as it should it has both of those files inside of it. The question is what would be the easiest way with minimal changes on js files to call showPictureList() function from utils.js file?
You can use ES2015/ES6 modules to import your functions which have been exported in another file. In your showPictures.js file you export the functions you want to expose, by adding the export keyword.
export function showPicturesList() {
if (!isEmpty($('#picture-name-list'))) {
var pictureList = document.getElementById("added-pictures");
pictureList.style.visibility = 'visible';
}
}
And then you need to import them in your util.js.
import { showPicturesList } from './showPictures';
For detailed informations on how to use modules you can have a look at Exploring JS: Modules.
With this you also don't need to add both files to entry in your webpack config, because webpack will see the imports and include eveything you're importing.

Categories

Resources