Squish 6.4 has added support for the JavaScript import
and export
statements from ECMAScript 2015 (ECMA-262). Here we list some advantages to using JavaScript modules over Squish’s source()
utility:
Namespaces
With source()
, the imported script is evaluated in the global namespace. This may result in unwanted name collisions and may make the overall code more prone to errors as your code base grows. It’s now possible to create a namespace for your imports, like so:
// constants.js export const PI = 3.14159; export const E = 2.71828; export const C = 299792458;
// test.js import * as constants from 'constants.js'; function main() { test.log( constants.PI ); }
This allows for partial imports, default imports or import aliases. You could also run the global code of a module without importing anything:
import 'side_effects.js';
(For the full overview on the syntax, see the JavaScript import and export documentation).
No import recursion
source()
evaluates a script line-by-line (similar to an #include
-directive from C/C++), which will lead to circular imports when you have scripts that import each other. JavaScript’s module imports are executed only once, avoiding this problem.
Debugging
The use of modules can also be more verbose (especially when naming imports), making it easier for you to find errors. For example, the following
// foobar.js export var foo = 42; var bar = "Hi!"; // not exported!
// test.js import {foo,bar} from 'foobar.js';
will result in a “Unknown export entry bar” script error being thrown by Squish.
Code completion
import
and export
are concepts from JavaScript itself, which means that they can be evaluated by the Squish IDE while you code. That is, you have access to IDE features such as code completion, refactoring and documentation for your modules.
Note: Squish will look for modules without absolute paths in the Test Case Resources (same folder as the test script itself), Test Script Resources (‘<suite folder>/shared/scripts’ folder) as well as any Global Scripts folder you specify.
Conclusion
Using the native script-language import syntax will help you organize your code even better.
We’re definitely a fan of it – even the new Scripted Object Map uses it!
The post Making Use of JavaScript Modules appeared first on froglogic.