### Initialize a new Node.js project
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Creates a new project folder, initializes it with npm, and sets up a basic HTML file. It also installs essential development and runtime dependencies like steal, steal-tools, and jquery.
```bash
> mkdir myhub
> cd myhub
> npm init
Hello World!
> npm install http-server -g
> http-server
> npm install steal --save
> npm install steal-tools --save-dev
> npm install jquery --save
```
--------------------------------
### StealJS Installation and Basic Setup
Source: https://context7.com/stealjs/steal/llms.txt
Instructions on how to install StealJS using npm and set up a basic project structure with an HTML file and a JavaScript entry point.
```APIDOC
## Installation and Basic Setup
### Description
Instructions on how to install StealJS using npm and set up a basic project structure with an HTML file and a JavaScript entry point.
### Method
Bash/Shell
### Endpoint
N/A
### Parameters
None
### Request Example
```bash
# Install steal and dependencies
npm install steal -S
npm install jquery
# Project structure
# /
# node_modules/
# package.json
# myapp.js
# myapp.html
```
### Response
None
## HTML Setup
### Description
Example of an HTML file that loads StealJS and specifies the main module.
### Method
HTML
### Endpoint
N/A
### Parameters
None
### Request Example
```html
```
### Response
None
## JavaScript Entry Point
### Description
Example of a JavaScript file that uses StealJS to import and use a module (jQuery in this case).
### Method
JavaScript
### Endpoint
N/A
### Parameters
None
### Request Example
```js
// myapp.js
import $ from "jquery";
$("body").append("
Hello World
");
```
### Response
None
```
--------------------------------
### Build Production App with Steal Tools
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This command executes the StealJS build process to create a production-ready version of the application. It uses the 'steal-tools' package to bundle and optimize all project assets, preparing them for deployment.
```bash
> ./node_modules/.bin/steal-tools
```
--------------------------------
### Create Production Index HTML
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This HTML file serves as the entry point for the production build. It includes the StealJS production build script and specifies the main module to load, ensuring the application runs correctly in a production environment.
```html
```
--------------------------------
### Create HTML Test Page for StealJS Module
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This HTML file sets up a basic page for testing StealJS modules. It includes the StealJS loader and specifies the main test file to be loaded. It also provides a fixture element for QUnit tests.
```html
myhub/repos/repos
```
--------------------------------
### Configure package.json for StealJS project
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Updates the package.json file to specify the main entry point for the StealJS application and lists the necessary dependencies and devDependencies, including steal and steal-tools.
```json
{
"name": "myhub",
"version": "1.0.0",
"description": "",
"main": "myhub.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.0.0",
"steal": "^0.16.21"
},
"devDependencies": {
"steal-tools": "^0.16.5"
}
}
```
--------------------------------
### Import LESS styles with StealJS
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Installs the steal-less package to enable processing of LESS files. It then demonstrates importing a LESS file into a JavaScript module, allowing for dynamic styling of HTML elements.
```bash
> npm install steal-less --save
body h1 {
color: #2193C4;
}
import $ from "jquery";
import "./myhub.less";
$("body").html("
Goodbye script tags!
");
```
--------------------------------
### Example: Initial Render and Reload Callback
Source: https://github.com/stealjs/steal/blob/master/docs/module-live-reload.md
This JavaScript example illustrates a common use case for `live-reload`: performing an initial render of the application and then re-rendering whenever a reload cycle is completed. This ensures that UI updates reflect the latest code changes.
```javascript
import reload from "live-reload";
import template from "./template.stache!";
function render() {
$("#app").html(template());
}
// Do the initial render.
render();
// Assign a callback that will be called whenever a reload cycle is complete.
// Call `render` again so that any code that changed code can take effect.
reload(function(){
render();
});
```
--------------------------------
### Start Live-Reload Server with Steal-Tools
Source: https://github.com/stealjs/steal/blob/master/docs/module-live-reload.md
This command-line instruction shows how to start a live-reload WebSocket server using the `steal-tools` package. This server is essential for the `live-reload` module to detect file changes and trigger reloads in the browser.
```bash
steal-tools live-reload
```
--------------------------------
### Create JavaScript Test for StealJS Module
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript file uses steal-qunit to test the GitHub repository module. It defines a basic test that checks if the module initially displays 'Loading...' and then inserts a data list. It requires steal-qunit and the repos module.
```javascript
import QUnit from "steal-qunit";
import repos from "./repos";
QUnit.module("myhub/repos/");
QUnit.test("basics", function(){
stop();
var fixtureEl = document.getElementById("qunit-fixture");
repos(fixtureEl);
QUnit.equal(
fixtureEl.innerHTML,
"Loading...", "starts with loading");
var interval = setInterval(function(){
var dl = fixtureEl.getElementsByTagName("dl");
if(dl.length === 1) {
QUnit.ok(true, "inserted a dl");
QUnit.start();
clearInterval(interval);
}
},100);
});
```
--------------------------------
### StealJS Initialization and Testing Setup
Source: https://github.com/stealjs/steal/blob/master/test/production_err/prod-inst.html
This JavaScript code initializes QUnit for testing and sets up the StealJS configuration. It assumes QUnit is available globally from the parent window and configures StealJS to recognize a CSS bundle.
```javascript
window.QUnit = window.parent.QUnit;
window.removeMyself = window.parent.removeMyself;
steal = {
instantiated: {
"bundles/bar.css!$css": null
}
};
```
--------------------------------
### Create and load an ES6 module with StealJS
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Sets up an HTML page to load a custom ES6 module named 'repos' using StealJS's steal.js loader. The script tag's 'main="@empty"' attribute and the inline import statement configure StealJS to load and execute the specified module.
```html
```
--------------------------------
### Bundle Steal.js for Production
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This command bundles the StealJS library itself into the production build, along with the application code. This can result in a single JavaScript file for the entire application, simplifying deployment and potentially improving load times.
```bash
> ./node_modules/.bin/steal-tools build --bundleSteal
```
--------------------------------
### Specify Plugins for StealJS
Source: https://github.com/stealjs/steal/blob/master/docs/module-npm.md
Lists packages that are utilized as plugins within StealJS. These plugins are prefetched, ensuring their configurations are applied before the main application starts. An example is 'steal-css'.
```json
{
"steal": {
"plugins": ["steal-css"]
}
}
```
--------------------------------
### SystemJS Test Environment Setup
Source: https://github.com/stealjs/steal/blob/master/test/npm/json-options/dev.html
Configures the SystemJS environment for testing by aliasing global 'done' and 'assert' functions from the parent window. This is commonly used in testing frameworks to provide assertion and completion callbacks.
```javascript
SystemJS tests window.done = window.parent.done; window.assert = window.parent.assert;
```
--------------------------------
### Setup Test Assertions and Done Callback
Source: https://github.com/stealjs/steal/blob/master/test/production/prod-inst.html
Initializes global assertion and done functions for testing environments, likely by referencing them from the parent window. This is common in iframe-based testing setups.
```javascript
window.assert = window.parent.assert; window.done = window.parent.done;
```
--------------------------------
### Create JavaScript Module for GitHub Repos
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript module fetches GitHub repositories for a given user using jQuery's AJAX. It requires jQuery and Bootstrap CSS. The module takes a CSS selector as input and updates the specified element with a list of repositories.
```javascript
import $ from "jquery";
import "bootstrap/dist/css/bootstrap.css";
export default function(selector){
$(selector).html("Loading...")
$.ajax({
url: "https://api.github.com/users/justinbmeyer/repos",
jsonp: "callback",
dataType: "jsonp",
success: function( response ) {
var defs = response.data.map(function(repo){
return `
");
}
});
}
```
--------------------------------
### Configure justifiedGallery Dependency in package.json
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JSON snippet demonstrates how to add 'justifiedGallery' and other necessary dependencies to a project's package.json file. It also includes StealJS-specific system configurations for mapping and meta-data, ensuring justifiedGallery is correctly loaded with its dependencies like jQuery and its LESS stylesheet.
```json
{
"name": "myhub",
"version": "1.0.0",
"description": "",
"main": "myhub.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^3.3.6",
"jquery": "^3.0.0",
"justifiedGallery": "^3.6.2",
"steal": "^0.16.21"
},
"devDependencies": {
"steal-qunit": "^0.1.1",
"steal-tools": "^0.16.5"
},
"system": {
"map": {
"justifiedGallery": "justifiedGallery/src/js/justifiedGallery"
},
"meta": {
"justifiedGallery/src/js/justifiedGallery": {
"format": "global",
"deps": ["jquery","justifiedGallery/src/less/justifiedGallery.less"]
}
}
}
}
```
--------------------------------
### Create StealJS Build Script
Source: https://github.com/stealjs/steal/wiki/Getting-Started
A JavaScript file that utilizes 'steal-tools' to perform a build process for the StealJS application. It configures the build using the project's package.json as the system configuration and enables the 'bundleSteal' option.
```javascript
var stealTools = require("steal-tools");
stealTools.build({
config: __dirname+"/package.json!npm"
}, {
bundleSteal: true
});
```
--------------------------------
### Install StealJS via npm
Source: https://github.com/stealjs/steal/blob/master/docs/steal.md
Installs the StealJS module loader and the jQuery library using npm. This is the first step for setting up a project that uses StealJS with npm.
```bash
> npm install steal -S
> npm install jquery
```
--------------------------------
### Create StealJS Export Script
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This script uses 'steal-tools' to export modules to different formats, such as AMD and global JavaScript. It specifies the main module, system configuration, and output options, including defining exports and destination paths for the generated files.
```javascript
var stealTools = require("steal-tools");
stealTools.export({
system: {
main: "myhub/repos/repos",
config: __dirname+"/package.json!npm"
},
options: {
verbose: true
},
outputs: {
"+amd": {},
"+global-js": {
exports: {
"myhub/repos/repos":"repos",
"jquery": "jQuery"
},
dest: __dirname+"/dist/global/repos.js"
}
}
});
```
--------------------------------
### Implement Progressive Loading in myhub.js
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript code modifies the main application file to enable progressive loading of modules. Instead of importing all modules at once, it uses `System.import()` to load modules dynamically based on the URL hash, improving initial load performance.
```javascript
import $ from "jquery";
import "./myhub.less";
import "bootstrap/dist/css/bootstrap.css";
$("body").append("
");
var updatePage = function(){
var hash = window.location.hash.substr(1);
if(!hash) {
$("#main").html("Welcome home");
} else {
System.import("myhub/"+hash+"/"+hash).then(function(moduleOrPlugin){
var plugin = typeof moduleOrPlugin === "function" ?
moduleOrPlugin : moduleOrPlugin["default"];
plugin("#main");
});
}
};
$(window).on("hashchange", updatePage);
updatePage();
```
--------------------------------
### Start StealJS Live Reload Server
Source: https://context7.com/stealjs/steal/llms.txt
Initiate the StealJS live-reload server using the `steal-tools live-reload` command in your terminal. This command starts a development server that watches for file changes and triggers browser reloads.
```bash
# Start live-reload server
steal-tools live-reload
```
--------------------------------
### Configure StealJS in package.json (npm)
Source: https://github.com/stealjs/steal/blob/master/docs/steal.md
Example of a package.json file configuring StealJS. It specifies the main module and dependencies, demonstrating how StealJS reads configuration from package.json.
```json
{
"name": "myapp",
"main": "myapp",
"dependencies": {
"jquery": "2.1.3"
},
"devDependencies": {...}
"steal": {
}
}
```
--------------------------------
### Use StealJS Module in Main Application
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript file demonstrates how to use the GitHub repository module in a main application file. It appends a container to the body and then calls the repos module to populate a div with the repository list. It requires jQuery, Bootstrap CSS, and the repos module.
```javascript
import $ from "jquery";
import "./myhub.less";
import "bootstrap/dist/css/bootstrap.css";
import repos from "./repos/repos";
$("body").append(
"
"+
"
Goodbye script tags!
"+
""+
"
");
repos('#repos');
```
--------------------------------
### Verify ES2015 Transpilation with StealJS
Source: https://github.com/stealjs/steal/blob/master/test/skip_es_2015_preset/site.html
This snippet tests the es-2015 preset by defining an async function and checking if its string representation matches the expected ES2015 format. It relies on `window.done` and `window.parent.assert` for testing and completion.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal = { forceES5: false };
export default function(){}
var p = new Promise(function(resolve) {
async function callMe() {}
resolve(callMe.toString());
});
p.then(function(fnName) {
assert.equal( fnName, "async function callMe() {", "it should not transpile ES2015 code" );
done();
})
.catch(function(e) {
assert.ok(!e, "it should not fail: " + e.message);
done();
});
```
--------------------------------
### Install StealJS and Dependencies
Source: https://context7.com/stealjs/steal/llms.txt
Installs StealJS and the jQuery library using npm. Assumes a project structure with node_modules, package.json, and application files.
```bash
# Install steal and dependencies
npm install steal -S
npm install jquery
# Project structure
# /
# node_modules/
# package.json
# myapp.js
# myapp.html
```
--------------------------------
### Assert StealJS Configuration Value
Source: https://github.com/stealjs/steal/blob/master/test/basics/truthy_script_options.html
This snippet configures StealJS with a 'foo' property set to true and then asserts that this configuration is correctly applied. It relies on the global `steal` object and expects `window.assert` and `window.done` to be available for testing.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal.done().then(function(){
if (window.assert) {
assert.ok(steal.config("foo") === true, "config's foo should be truthy");
done();
}
});
```
--------------------------------
### Create HTML for Global Script Integration
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This HTML file demonstrates how to import a global script (justifiedGallery) into a CommonJS module using StealJS. It includes the StealJS loader and uses a script tag with `main="@empty"` to execute custom script logic for requiring and using the module.
```html
```
--------------------------------
### NPM Package Versioning Example
Source: https://github.com/stealjs/steal/blob/master/docs/type-moduleName.md
Illustrates how StealJS handles versioning for npm packages when multiple dependencies require different, yet semver-compatible, versions of the same package.
```javascript
// Dependency 1: "foo": "^1.0.0"
// Dependency 2: "foo": "^1.1.0"
// Both will resolve to a module name like: foo@1.1.0#main
```
--------------------------------
### Initialize StealJS Configuration
Source: https://github.com/stealjs/steal/blob/master/test/stealconfig/dev.html
Initializes the StealJS configuration object with the path to the configuration file and the main module. This is typically done at the start of a StealJS application to define its build and loading behavior.
```javascript
var steal = { "configPath": "ssd/js/stealconfig.js", "main": "main" };
```
--------------------------------
### Configure Module Loading and Assertions in StealJS
Source: https://github.com/stealjs/steal/blob/master/test/load_module_twice_false_positive/dev.html
This snippet configures StealJS to handle module loading and sets up global assertion and completion functions. It overrides console.warn to test for duplicate module loading warnings and asserts the successful completion of the StealJS process.
```javascript
window.assert = window.parent.assert;
window.done = window.parent.done;
window.WARN = Function.prototype.bind.call( window.console.warn, window.console );
window.console.warn = function(msg) {
window.assert.ok( !/is being instantiated twice/.test(msg), "steal should not warn users when a module was loaded before the config" );
window.WARN.apply(this, arguments);
};
steal.done().then(function(){
if(window.assert) {
window.assert.ok(true, 'finished without throwing');
window.done();
} else {
console.log('Finished without throwing!');
}
});
```
--------------------------------
### StealJS Module Import and Tree Shaking Verification
Source: https://github.com/stealjs/steal/blob/master/test/tree_shake/bundle.html
Imports modules using StealJS and verifies the contents of a specific module ('shake@1.0.0#mod') after potential tree shaking. It uses `window.assert` for assertions if available, otherwise logs the module to the console.
```javascript
Project: /stealjs/steal
Content:
Tree shaking window.assert = window.parent.assert; window.done = window.parent.done; var newSteal;
function checkEverything() {
var loader = newSteal.loader;
var mod = loader.get("shake@1.0.0#mod");
if(window.assert) {
window.assert.equal(mod.a, "a");
window.assert.equal(mod.c, "c");
window.assert.equal(mod.d, "d");
window.done();
} else {
console.log(mod);
}
}
var lastSteal = steal;
function clone() {
newSteal = lastSteal.clone();
lastSteal.loader._newLoader(newSteal.loader);
newSteal.loader.systemName = "cloned";
lastSteal = newSteal;
return newSteal;
}
steal.loader.systemName = "main";
steal.import("~/main")
.then(function() {
// Import something that has less stuff.
// This tests that ~/main carries forward.
return clone().import("~/mod_a");
})
.then(function(){
return clone().import("~/bundle").then(checkEverything);
});
```
--------------------------------
### Configure package.steal.main for npm plugin
Source: https://github.com/stealjs/steal/blob/master/docs/module-npm.md
Explains how to set the 'steal.main' property within package.json to define the main module for a package when it's imported. This determines the entry point module name, like 'my-main' in the example.
```json
{
"name": "my-module",
"version": "1.2.3",
"steal": {
"main": "my-main"
}
}
```
--------------------------------
### NPM Package Import Example
Source: https://github.com/stealjs/steal/blob/master/docs/type-moduleName.md
Shows how importing an npm package like 'lodash' is normalized into a module name that includes the package version and main module path, ensuring semver compatibility.
```javascript
import _ from "lodash"; // Normalizes to lodash@1.0.0#main if lodash is a dependency
```
--------------------------------
### Configure package.steal.meta for npm plugin
Source: https://github.com/stealjs/steal/blob/master/docs/module-npm.md
Illustrates setting the 'steal.meta' property in package.json to apply metadata to modules. Module names must start with './' for internal modules or look like 'packageName#./modulePath' for dependencies.
```javascript
{
"steal": {
"meta": {
"./src/utils": {"format": "amd"},
"jquery": {"format": "global"},
"lodash#./array/grep": {"format": "es6"}
}
}
}
```
--------------------------------
### Import Bootstrap CSS with StealJS
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Installs the Bootstrap CSS framework and imports it into the main JavaScript file using StealJS. This allows for the application of Bootstrap's styling to HTML elements, including layout containers and headings.
```javascript
import $ from "jquery";
import "./myhub.less";
import "bootstrap/dist/css/bootstrap.css";
$("body").append(
"
"+
"
Goodbye script tags!
"+
"
");
```
--------------------------------
### Import jQuery and update page content with StealJS
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript snippet demonstrates how to import the jQuery library using ES6 import syntax and then use it to modify the HTML content of the page. It requires jQuery to be installed as a dependency.
```javascript
import $ from "jquery";
$("body").html("
Goodbye script tags!
");
```
--------------------------------
### StealJS Development Bundle Loading and Verification
Source: https://github.com/stealjs/steal/blob/master/test/dev_bundles/deps.html
This snippet initializes global assertion functions and then waits for StealJS to complete loading its development bundle. It includes assertions to verify that the configuration loads first and the development bundle loads afterward. If assertions are not available, it logs the loading status.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal.done().then(function() {
if (window.assert != null) {
assert.equal(window.first, "configMain", "config should load first");
assert.equal(window.last, "bundle", "dev bundle should load after config");
done();
} else {
console.log("first loaded: ", window.first);
console.log("last loaded: ", window.last);
}
});
```
--------------------------------
### StealJS Initialization and Module Import with Error Handling (JavaScript)
Source: https://github.com/stealjs/steal/blob/master/test/syntax_errs/build.html
This snippet initializes StealJS, sets up a plugin loader, and imports a module. It includes error handling for the import process, with specific logic for browsers that have limited stack trace capabilities. Assertions are used to verify the import outcome.
```javascript
window.assert = window.parent.assert;
window.done = window.parent.done;
var pluginSteal = steal.clone();
steal.loader.pluginLoader = pluginSteal.loader;
steal.loader.set("@@babel-code-frame", steal.loader.newModule({}));
pluginSteal.startup()
.then(function(){
return steal.import("~/importer");
})
.then(null, function(err){
// IE and Safari don’t give good stack traces for this.
var browserDoesntSupportGoodStackTraces = /Function code/.test(err.stack) || /anonymous/.test(err.stack);
if(window.assert) {
if(browserDoesntSupportGoodStackTraces) {
window.assert.ok(true);
} else {
window.assert.ok(/breaking\.js/.test(err.stack), "Breaking file in the stack trace");
}
window.done();
} else {
console.error(err);
console.log('Did error!');
}
});
```
--------------------------------
### Update package.json for StealJS Bundles
Source: https://github.com/stealjs/steal/wiki/Getting-Started
Modifies the package.json file to include necessary dependencies and configurations for StealJS bundling. This includes defining 'steal-tools' and 'steal-qunit' as devDependencies and specifying bundle configurations within the 'system' property.
```json
{
"name": "myhub",
"version": "1.0.0",
"description": "",
"main": "myhub.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^3.3.6",
"jquery": "^3.0.0",
"justifiedGallery": "^3.6.2",
"steal": "^0.16.21"
},
"devDependencies": {
"steal-tools": "^0.16.5",
"steal-qunit": "^0.1.1"
},
"system": {
"map": {
"justifiedGallery": "justifiedGallery/src/js/justifiedGallery"
},
"meta": {
"justifiedGallery/src/js/justifiedGallery": {
"format": "global",
"deps": ["jquery","justifiedGallery/src/less/justifiedGallery.less"]
}
},
"bundle": [
"myhub/puppies/puppies",
"myhub/repos/repos"
]
}
}
```
--------------------------------
### Configure StealJS Main Modules and Handle Completion
Source: https://github.com/stealjs/steal/blob/master/test/multi-main/dev.html
This snippet shows how to set global `done` and `assert` functions, configure StealJS with an array of main modules, and then use the `steal.done()` promise to assert that all main modules have loaded successfully before calling the global `done` function.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal = { loadMainOnStartup: true, main: ["main1", "main2", "main3"] };
steal.done().then(function(){
assert.ok(main1, "main1");
assert.ok(main2, "main2");
assert.ok(main3, "main3");
done();
});
```
--------------------------------
### Import Main Package and Application Module with Assertions
Source: https://github.com/stealjs/steal/blob/master/test/npm/peer_deps/dev.html
This code imports the 'package.json!npm' to load npm dependencies and then imports the main application module specified by System.main. It includes a test assertion to check if the 'fourOhFours' counter is zero, indicating no 404 errors, and calls 'done()' upon successful completion. Error handling is also included.
```javascript
System.import("package.json!npm")
.then(function(){
return System.import(System.main);
})
.then(function(){
if(window.assert) {
assert.equal(fourOhFours, 0, "there were no 404s");
done();
}
})
.catch(function(e){
if(window.assert) {
assert.ok(false, e);
done();
} else {
console.log(e);
setTimeout(function(){
throw e;
});
}
});
```
--------------------------------
### Test Standalone Module with HTML
Source: https://github.com/stealjs/steal/wiki/Getting-Started
An HTML file designed to test a standalone JavaScript module exported from a StealJS build. It includes necessary CSS and JavaScript dependencies, loads the exported global module, and then calls the module's functionality.
```html
```
--------------------------------
### Create JavaScript Module for Global Script Usage
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript module is designed to be used with a global script like justifiedGallery. It uses `require` to import the global script and then exports a function that can be called to initialize the module. It requires the 'justifiedGallery' package.
```javascript
require("justifiedGallery");
module.exports = function(selector) {
};
```
--------------------------------
### StealJS: Loading Code Inline with steal-module
Source: https://github.com/stealjs/steal/blob/master/docs/config-main.md
This example shows how to load JavaScript code directly within an HTML file using the `steal-module` script type, without explicitly defining a `main` entry point. This is useful for demo pages or when writing inline code that doesn't require a separate module file. The `steal.js` script is included, followed by the `steal-module` script containing the inline code.
```javascript
```
--------------------------------
### Configure SystemJS and Import Package (JavaScript)
Source: https://github.com/stealjs/steal/blob/master/test/npm/config_deps/dev.html
Configures SystemJS with initial dependencies and imports a package. It then checks for QUnit and asserts specific dependency values. Errors are caught and logged.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
System.configDependencies = [ "global" ];
function hasQUnit() {
return typeof window.assert !== "undefined";
}
System["import"]("package.json!npm").then(function() {
var rootPkg = System.npmPaths.__default;
if(hasQUnit()) {
assert.equal(window.DEP, "this is a config dep");
assert.notEqual(System.configDependencies[0], "my-dep", "An npm dependency's configDependencies should not be part of the configDependencies array.");
assert.ok(rootPkg.steal.configDependencies, "there are config deps in the pkg");
} else {
console.log(window.DEP);
}
}).then(null, function(err){
console.error("Oh no, error!", err);
}).then(function(){
window.done && done();
});
```
--------------------------------
### Initialize and Import Tests for npm Extension
Source: https://github.com/stealjs/steal/blob/master/test/npm/test.html
This code snippet disables QUnit's autostart feature and then imports the 'package.json' module using the 'npm' plugin, followed by importing the main test module. This sets up the testing environment and begins the test execution.
```javascript
QUnit.config.autostart = false;
System.import("test/npm/package.json!npm").then(function(){
System.import("test/npm/test");
});
```
--------------------------------
### Import Modules with SystemJS and Handle Errors (JavaScript)
Source: https://github.com/stealjs/steal/blob/master/test/npm/parent/dev.html
This JavaScript code uses SystemJS to import modules. It first imports 'package.json!npm' and then the main system module. Error handling is included to log any issues encountered during the import process. This is typically used in testing setups.
```javascript
window.assert = window.parent.assert;
window.done = window.parent.done;
System.import("package.json!npm")
.then(function(){
return System.import(System.main);
})
.then(null, function(err){
console.error("Oh no, error!", err);
});
```
--------------------------------
### Update Index HTML to Use Bundled Steal.js
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This HTML file is updated to reference the bundled StealJS script instead of the individual production script. This configuration is used after running 'steal-tools build --bundleSteal', ensuring the application loads the pre-bundled StealJS runtime.
```html
```
--------------------------------
### Use justifiedGallery to Display Flickr Photos
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript code snippet shows how to use the 'justifiedGallery' plugin to display public photos from Flickr based on a tag. It utilizes jQuery for AJAX requests and DOM manipulation, dynamically fetching images and then applying the justifiedGallery plugin to arrange them.
```javascript
require("justifiedGallery");
var $ = require("jquery");
module.exports = function(selector) {
$(selector).html("Loading...");
$.ajax({
url: 'https://api.flickr.com/services/feeds/photos_public.gne',
dataType: 'jsonp',
jsonpCallback: "jsonFlickrFeed",
data: {
"tags": "puppy",
"format": "json"
},
success: function(response) {
var html = response.items.map(function(item, index) {
return ''
}).join("");
$(selector).html(html).justifiedGallery();
}
});
};
```
--------------------------------
### Configure package.main for npm plugin
Source: https://github.com/stealjs/steal/blob/master/docs/module-npm.md
Demonstrates how to set the 'main' property in a package.json file to specify the entry point for a package when used with the StealJS npm plugin. This is used to define the primary module to be loaded.
```json
{
"main": "myapp"
}
```
--------------------------------
### Test StealJS Module with Dependency Injection
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript test file extends the basic test by incorporating dependency injection using steal-clone. It mocks jQuery and its AJAX method to control the response, allowing for more isolated testing of the repos module. It requires steal-qunit, steal-clone, and jQuery.
```javascript
import QUnit from "steal-qunit";
import repos from "./repos";
import clone from 'steal-clone';
import $ from 'jquery';
QUnit.module("myhub/repos/");
QUnit.test("basics", function(){
QUnit.stop();
var fixtureEl = document.getElementById("qunit-fixture");
repos(fixtureEl);
QUnit.equal(
fixtureEl.innerHTML,
"Loading...", "starts with loading");
var interval = setInterval(function(){
var dl = fixtureEl.getElementsByTagName("dl");
if(dl.length === 1) {
QUnit.ok(true, "inserted a dl");
QUnit.start();
clearInterval(interval);
}
},100);
});
QUnit.asyncTest("basics with dependency injection", function(){
var jQuery = function(selector){
return $(selector)
};
jQuery.ajax = function(options){
setTimeout(function(){
options.success({
data: [{
url: "http://stealjs.com",
name: "StealJS",
description: "Futuristic Module Loader"
}]
});
QUnit.equal(
$("#qunit-fixture").html(),
'
',
"updated with request");
QUnit.start();
},1);
};
clone({
"jquery": {"default": jQuery}
}).import("myhub/repos/repos").then(function(module){
var repos = module["default"];
var fixtureEl = document.getElementById("qunit-fixture");
repos(fixtureEl);
});
});
```
--------------------------------
### Preload CSS in Production Index HTML
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This HTML snippet demonstrates how to preload CSS files in a production StealJS application. By adding a link tag for the generated CSS bundle and configuring StealJS's 'instantiated' property, the CSS is loaded before the main JavaScript bundle, improving perceived performance.
```html
```
--------------------------------
### Importing Bootstrap in LESS using locate://
Source: https://github.com/stealjs/steal/blob/master/docs/scheme-locate.md
Demonstrates how to import the Bootstrap LESS file from an npm module using the 'locate://' scheme within a LESS stylesheet. This example shows the original 'locate://' import and how StealJS rewrites it to a relative path.
```less
@import 'locate://bootstrap/less/bootstrap.less';
```
```less
@import '../../node_modules/bootstrap/less/bootstrap.less'
```
--------------------------------
### StealJS Development Bundle Loading and Assertion
Source: https://github.com/stealjs/steal/blob/master/test/dev_bundles/dev.html
This JavaScript code snippet configures StealJS to load development bundles. It sets global variables `done` and `assert` from the parent window and uses `steal.done().then()` to execute assertions once all bundles are loaded. It verifies that the 'bundle' loads first and 'configMain' loads after the bundle.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal.done().then(function() {
if (window.assert) {
assert.equal(window.first, "bundle", "dev bundle should load first");
assert.equal(window.last, "configMain", "config should load after bundle");
done();
} else {
console.log("first loaded: ", window.first);
console.log("last loaded: ", window.last);
}
});
```
--------------------------------
### Update myhub.js for Production App Routing
Source: https://github.com/stealjs/steal/wiki/Getting-Started
This JavaScript code updates the main application file ('myhub.js') to include routing using browser hash changes. It imports necessary modules like jQuery and Bootstrap, sets up basic HTML structure, and defines a simple module loader to handle navigation between different sections ('repos', 'puppies', or a default home page).
```javascript
import $ from "jquery";
import "./myhub.less";
import "bootstrap/dist/css/bootstrap.css";
import repos from "./repos/repos";
import puppies from "./puppies/puppies";
$("body").append("
");
var modules = {
repos: repos,
puppies: puppies,
"": function(selector){
$(selector).html("Welcome home");
}
};
var updatePage = function(){
var hash = window.location.hash.substr(1);
modules[hash]("#main");
};
$(window).on("hashchange", updateUpdatePage);
updatePage();
```
--------------------------------
### Configure StealJS Main Entry Point via JavaScript Configuration
Source: https://github.com/stealjs/steal/blob/master/docs/config-main.md
This code illustrates how to configure the main entry point for StealJS using a JavaScript configuration object, typically within build tools like `steal-tools`. It shows how to specify the main module when building the application. This configuration can also be set inline in HTML before the StealJS script tag.
```javascript
const stealTools = require("steal-tools");
stealTools.build({
config: __dirname + "/package.json!npm",
main: "todo-app/app"
});
```
```javascript
steal = {
baseURL: "/apps/todos",
main: "~/main"
};
```
--------------------------------
### Set up Test Utilities and Global Assertions
Source: https://github.com/stealjs/steal/blob/master/test/bad_json/dev.html
Initializes global assertion and completion functions by referencing them from the parent window. It also overrides `window.console.warn` to assert on warnings, indicating potential issues like using steal-clone.
```javascript
window.assert = window.parent.assert;
window.done = window.parent.done;
window.WARN = Function.prototype.bind.call( window.console.warn, window.console );
window.console.warn = function(msg) {
window.assert.ok( false, "Warning caused by using steal-clone" );
window.WARN(msg);
};
```
--------------------------------
### Configure Babel Polyfill for Generators
Source: https://github.com/stealjs/steal/blob/master/docs/config-babelOptions.md
Provides instructions on installing and configuring the Babel polyfill for Generator support in StealJS. This involves installing the package and updating the package.json with 'map' and 'meta' configurations for proper loading.
```json
{
"steal": {
...
"map": {
"babel-polyfill": "babel-polyfill/dist/polyfill"
},
"meta": {
"babel-polyfill/dist/polyfill": {
"format": "cjs"
}
}
}
}
```
--------------------------------
### Initialize StealJS with Async Script Loading
Source: https://github.com/stealjs/steal/blob/master/test/async-script/index.html
This snippet demonstrates how to initialize StealJS by asynchronously loading 'async.js'. It sets up global 'done' and 'assert' functions, likely for testing or module management, and then creates and appends a script tag to the document's head after a short delay.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
setTimeout(function(){
var s = document.createElement("script");
s.src = 'async.js';
document.head.appendChild(s);
}, 1);
```
--------------------------------
### Asynchronous Module Loading and Assertion with StealJS
Source: https://github.com/stealjs/steal/blob/master/test/cjs_export_default/dev.html
This snippet demonstrates loading two modules ('~/index' and '~/es') sequentially using StealJS's `import` method. It utilizes Promises to handle the asynchronous loading and includes checks using a global `assert` function for validation. If `assert` is not available, it logs the loaded modules to the console. The `done` function is called upon successful completion or error.
```javascript
window.done = window.parent.done;
window.assert = window.parent.assert;
steal.import("~/index")
.then(function(index){
if(window.assert) {
window.assert.equal(index.foo, "bar", "loaded correctly");
} else {
console.log("index module:", index);
}
return steal.import("~/es");
})
.then(function(es) {
if(window.assert) {
window.assert.equal(es.default.default, "//", "comment in a string");
window.done();
} else {
console.log("es module", es);
}
})
.catch(function(err) {
if(window.assert) {
window.assert.ok(false, err);
window.done();
} else {
console.error("Oops", err);
}
});
```
--------------------------------
### Default configMain with npm
Source: https://github.com/stealjs/steal/blob/master/docs/config-configMain.md
Illustrates the default value of configMain when StealJS is installed via npm and used in a project. In this scenario, configMain is set to 'package.json!npm'.
```html
```
--------------------------------
### Initialize StealJS Main Module and Load Application
Source: https://github.com/stealjs/steal/blob/master/test/main-warn/delayed.html
This snippet initializes StealJS by setting the warning threshold and then asynchronously imports the 'main' module after a short delay. It also schedules a function to report all collected warnings.
```javascript
steal._mainWarnMs = 100;
steal.done().then(function(){
setTimeout(function(){
System.import("main");
}, 50);
setTimeout(function(){
window.report(window.allWarnings);
}, 100);
});
```
--------------------------------
### steal.import() Dynamic Importing
Source: https://context7.com/stealjs/steal/llms.txt
Documentation for dynamically importing modules after initial configuration. It supports single or multiple module names and returns a Promise.
```APIDOC
## steal.import()
### Description
Dynamically imports modules after initial configuration has loaded. Waits for configMain to be loaded before importing, supports multiple module names, and returns a Promise.
### Method
JavaScript
### Endpoint
N/A
### Parameters
None
### Request Example
```js
// Browser usage - single module
// Browser usage - multiple modules
steal.import("jquery", "lodash", "my-component").then(function($, _, MyComponent) {
var component = new MyComponent();
$("#app").append(component.render());
});
// Node.js usage
var steal = require("steal").clone();
steal.import("server/main").then(function(serverMain) {
serverMain.startServer(3000);
});
// Progressive loading based on route
if (window.location.pathname === "/checkout") {
steal.import("pages/checkout").then(function(checkout) {
checkout.render();
});
}
```
### Response
None
```
--------------------------------
### Configure StealJS Paths in config.js (Download)
Source: https://github.com/stealjs/steal/blob/master/docs/steal.md
Configures StealJS by setting module paths, such as loading jQuery from a CDN. This file is used when StealJS is installed via download.
```javascript
// config.js
steal.config({
paths: {"jquery": "http://code.jquery.com/jquery-1.11.0.min.js"}
});
```