简体   繁体   中英

Javascript - Create exportable dynamic code

Hi any help or links to similar questions is greatly appreciated as I have done a bit of research but am not sure on the most correct path here.

I dont really know how to explain exactly what i want so i drew this picture that might help explain a bit:

在此处输入图像描述

Currently i have all written in 1 file and would like to make it more modular so others can code there own 'strategy's' using system objects and so on.

The main goal here is that i can change all the system code in one place because i have many strategies and if i want to update the system code to add more results etc.. i need to change it in many files.

A good comparison i can see to this is the npm module testcafe. Once downloaded how you use it in your code is similar:

import testcafe

test(testName, => { all the code you want to run is here and you have many 
objects and functions provided from testcafe you can use})

My guess would be to achieve this maybe i need global classes, maybe a class called strategy and inside of it is all the objects, functions, for loop, log results, etc..

Things i worry about:

  1. how to integrate the user defined globals into the strategy
  2. how to make it so that when the user types in there IDE they dont get red errors for the globals they defined and the functions and objects that exist outside in the system code.

This is all pretty high level, im not looking for exact code to type to solve it all (of course would be nice:) ) but more looking for pointers, ideas, and paths i should research. Any help is highly appreciated!

Don't export something from the user file that the system file would import. Make use of dependency inversion and only have the user code depend on the system code. Since the user code is the entry point of the application anyway, that's easy.

In the system code file, export a function that takes the strategy as a parameter and runs the main loop. No need to "import" anything.

// system.js
import … from 'environment';

/* declarations */
export function utility() { … }

/* the loop */
export function run(strategy) {
  let … // more declarations
  for (…) {
    …
    step = strategy(newValues)
    …
  }
  console.log(results);
}
// userFile.js
import { utility, run } from 'system';

let … // globals
run((…) => {
  … // use globals, loop arguments and imported utilities
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM