New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

als-require

Package Overview
Dependencies
Maintainers
0
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

als-require - npm Package Compare versions

Comparing version 0.2.0 to 0.3.0

browser-tests/build.js

5

index.js

@@ -1,4 +0,3 @@

const getModule = require('./lib/get-module')
const Require = require('./lib/require')
const Modules = require('./lib/modules')
module.exports = { getModule, Require }
module.exports = Modules

35

lib/get-module.js
const fs = require('fs')
const { join } = require('path')
const calledFrom = require('./called-from')
function getRequire(path, varName) {
const calledFrom = require('als-called-from')
function getModule(path) {
const calledPath = calledFrom()

@@ -14,20 +13,20 @@ if (!path.endsWith('.js')) path += '.js'

}
const modulPaths = new Set()
const modules = {},curDirParts = __dirname.split(/\\|\//);
let curModule = module.children.filter(mod => mod.filename.replace(/\\/g, '/').endsWith(path.replace(/^\./, '')))[0]
function addFilename(mod) {
if (modulPaths.has(mod.filename)) return
modulPaths.add(mod.filename)
mod.children.forEach(child => {
addFilename(child)
});
function addModule(mod) {
const path = mod.filename
const relativePath = path.split(/\\|\//).filter((part,i) => curDirParts[i] !== part).join('/')
if(modules[relativePath]) return
if(getModule.cache[relativePath]) modules[relativePath] = getModule.cache[relativePath]
else {
modules[relativePath] = {exports:mod.exports,content:fs.readFileSync(path, 'utf-8')}
getModule.cache[relativePath] = modules[relativePath]
}
mod.children.forEach(child => addModule(child));
}
addFilename(curModule)
const obj = {}
modulPaths.forEach(path => {
obj[path.replace(__dirname, '').replace(/\\/g, '/')] = fs.readFileSync(path, 'utf-8')
});
return `const ${varName} = getModule.buildModules(${JSON.stringify(obj)})`
addModule(curModule)
return modules
}
module.exports = getRequire
getModule.cache = {}
module.exports = getModule
{
"name": "als-require",
"version": "0.2.0",
"version": "0.3.0",
"description": "A utility for using CommonJS require in the browser and creating bundles.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "node --test --experimental-test-coverage",
"get-module": "node --test ./tests/get-module.test.js",
"get-module-only": "node --test-only ./tests/get-module.test.js",
"get-module-coverage": "node --test --experimental-test-coverage ./tests/get-module.test.js",
"get-module-report": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info ./tests/get-module.test.js",
"modules": "node --test ./tests/modules.test.js",
"modules-only": "node --test-only ./tests/modules.test.js",
"modules-coverage": "node --test --experimental-test-coverage ./tests/modules.test.js",
"modules-report": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info ./tests/modules.test.js"
},

@@ -19,3 +27,5 @@ "keywords": [

"license": "MIT",
"dependencies": {}
}
"dependencies": {
"als-called-from": "^1.0.0"
}
}

@@ -21,22 +21,20 @@ # als-require

## Overview of `als-require`
## Usage
`als-require` includes two main components designed to enhance module handling in web browsers and server environments. It facilitates the use of CommonJS modules directly in the browser and supports the generation of module bundles for more efficient deployment.
`als-require` includes two main parts:
1. Browser's script for handling modules
2. Bundle builder for browser
### Components
### Dynamic Module Loading in Browsers
1. **Browser Script (`require.js`)**: This script is used in the browser to dynamically load and resolve modules. It allows for direct module usage without pre-bundling, enabling more flexible and dynamic web applications.
The browser's script called `getModule`, is a function which fetching all module's chain and then laughing all the chain to get the result.
The fetch is async, that's why `getModule` returns promise.
All module's results, saved in `getModule.modules` object with relative path as a key and module result as a value.
2. **Bundle Generator Script (`index.js`)**: This Node.js script is used to generate bundles of CommonJS modules, which can then be included in web projects. It simplifies the deployment process by compiling dependencies into a single file.
### Usage Scenarios
`als-require` can be utilized in two primary ways:
#### 1. Direct Browser Usage
In this scenario, the `require.js` script dynamically loads the modules directly in the browser. This is suitable for environments where modules need to be loaded on the fly without pre-compilation.
**Example:**
Let's say, we have moduleA.js which requiring another modules and exporting variable `someExport` and we want to use this module in browser.
Here is the code:
```html

@@ -51,5 +49,5 @@ <!DOCTYPE html>

<script>
getModule('./module1/a.js')
.then(someExport => {
getModule('./moduleA.js').then(someExport => {
window.someExport = someExport;
console.log(getModule.modules) // will return object with all modules and their results
});

@@ -61,4 +59,7 @@ </script>

#### 2. Bundle Creation and Usage
In example above, first we include `als-require` script which adding `getModule` function and then, get the module.
### Creating and Using Bundles
In this scenario, `als-require` is used to generate a bundle that consolidates all the required modules into a single file. This bundle can then be used in the browser, reducing the number of HTTP requests and streamlining the module loading process.

@@ -69,46 +70,28 @@

```javascript
const fs = require('fs');
const { getModule , Require } = require('als-require');
const script = getModule('./module1/a', 'test'); // generates bundle from module
fs.writeFileSync('test.js', script);
```
const Modules = require('als-require');
const modules = new Modules()
modules.require('./moduleA','moduleAVarname')
modules.require('./moduleB','moduleBVarname')
This bundle can also be served directly from a server using frameworks like Express:
modules.scripts // the object with {relativePath:{exports,content}}
```javascript
const modules = new Require()
modules.require('./module1/a', 'module1')
modules.require('./some/b', 'module2')
// Now you can save the script as file
require('fs').writeFileSync('test.js', modules.script);
// Or return it directly
app.get('/bundle.js', (req, res) => {
res.send(modules.script); // indludes browser's script (require.js)
res.send(modules.script);
});
```
## API Reference
### `getRequire(path, varName)`
Loads a module from the specified `path` and assigns it to a variable named `varName`.
- **path**: `String` - The relative path to the module file.
- **varName**: `String` - The variable name to which the module's exports will be assigned.
## Examples
### Loading a Simple Module
```javascript
const config = getModule('./config', 'config');
console.log(config);
On Browser:
```html
<script src="/bundle.js"></script>
<script>
console.log(moduleAVarname,moduleBVarname)
console.log(getModule.modules)
</script>
```
### Handling Errors
The bundle is self-sufficient and will include getModule with `getModule.modules` which will include all bundled modules.
```javascript
try {
const result = getModule('./invalid/path', 'test');
} catch (error) {
console.error('Failed to load module:', error.message);
}
```

@@ -57,6 +57,8 @@ async function getModule(path, errors = []) {

else modules[path] = module
getModule.modules[path] = modules[path]
})
const result = modules[keys[keys.length - 1]]
return result
}
}
getModule.modules = {}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc