npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

scoped-amd-library-plugin

v0.1.4

Published

[![Run tests](https://github.com/lirancr/scoped-amd-library-plugin/actions/workflows/test.yml/badge.svg)](https://github.com/lirancr/scoped-amd-library-plugin/actions/workflows/test.yml) [![NPM Version](https://badge.fury.io/js/scoped-amd-library-plugin.s

Downloads

23

Readme

Run tests NPM Version

Scoped AMD Library Webpack Plugin

This plugin is based on Webpack's AmdLibraryPlugin

This plugin let you create amd bundles that do not use your environment globals from Webpack's own runtime and use your own global scope implementation instead. This may come in handy in cases where you wish to load multiple pieces of code written by a trusted party without having them polluting your global scope. As a library owner who use this plugin, your output will be expecting your consumer to provide you with a global analog.

Additionally, you may use this plugin to provide an easy way for your library consumer to load it in a different environment than it was originally packaged for (e.g. consume amd bundles built for node targets in the browser) without bloating your bundle with the additional runtime code required for a full-blown umd bundle format or creating duplicate bundle files for each target.

Webpack versions support

Webpack 5

Usage

  1. Install package
    npm install scoped-amd-library-plugin
  2. Set library.type configuration to scoped-amd.
  3. Set the externalsType configuration to amd.
  4. Add plugin to plugins list and pass the scope dependency name which will be provided by your amd loader.
    const { ScopedAmdLibraryPlugin } = require('scoped-amd-library-plugin')
    new ScopedAmdLibraryPlugin({ scopeDependencyName: 'myScope' })
  5. Use the ProvidePlugin point any global namespaces your code access (and you wish to scope) to your scope dependency.
  6. If your scope is not provided from a npm library but rather directly by you at runtime, declare your scope dependency as external by adding it to the externals array. Otherwise, webpack will look it up in your node_modules directory and fail

Following the steps above, your configuration file would end up looking something like this:

webpack.config.js

const { ProvidePlugin } = require('webpack')
const { ScopedAmdLibraryPlugin } = require('scoped-amd-library-plugin')

const scopeDependencyName = 'myScope'

module.exports = {
	output: {
		library: {
			type: 'scoped-amd', // step 1
		},
	},
	externalsType: 'amd', // step 2
	plugins: [
		new ScopedAmdLibraryPlugin({ scopeDependencyName }), // step 3
		new ProvidePlugin({
			// step 4
			window: scopeDependencyName,
			document: [scopeDependencyName, 'document'],
			fetch: [scopeDependencyName, 'fetch'],
		}),
	],
	externals: [
		{
			[scopeDependencyName]: scopeDependencyName, // optional step 5
		},
	],
}

output example

Assuming our code include these source files

index.js

const chunk = import('./chunky' /* webpackChunkName: "chunky" */)
export const indexPromise = fetch('http://localhost:8080')
export const chunkyPromise = chunk

chunky.js

export const msg = 'msg from chunk'
export const chunkyPromise = fetch('http://localhost:8080/chunky')

Using the configuration above, webpack will output something like this:

index.bundle.js

// myScope declared as external so it's expected as one of the amd's dependencies
define(['myScope'], (__WEBPACK_EXTERNAL_MODULE__106__) => {
	// ScopedAmdLibraryPlugin adds global objects shadow vars (default build target is web)
	const globalThis = __WEBPACK_EXTERNAL_MODULE__106__
	const window = __WEBPACK_EXTERNAL_MODULE__106__
	const document = (__WEBPACK_EXTERNAL_MODULE__106__.document =
		__WEBPACK_EXTERNAL_MODULE__106__.document || __WEBPACK_EXTERNAL_MODULE__106__)
	return (() => {
		// ProvidePlugin replaces global fetch access with myScope.fetch which is from our dependencies
		var fetch = __webpack_require__(106)['fetch']
		const chunk = __webpack_require__
			.e(/* import() | chunky */ 427)
			.then(__webpack_require__.bind(__webpack_require__, 198))(() => {
			const indexPromise = fetch('http://localhost:8080')
			const chunkyPromise = chunk
		})()
	})()
})

chunky.chunk.js

;(self['webpackChunkproject_name'] = self['webpackChunkproject_name'] || []).push([
	[427],
	{
		198: (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
			// ProvidePlugin replaces global fetch access with myScope.fetch which is from our dependencies
			var fetch = __webpack_require__(106)['fetch']
			const msg = 'msg from chunk'
			const chunkyPromise = fetch('http://localhost:8080/chunky')
		},
	},
])

Global factories

In addition to the plugin itself, this library also comes packaged with global scope object factories which create the minimal global object implementation needed to load amd files generated for each supported target. These implementations are completely environment independent and require no additional code so you can use the web scope factory in node and vice versa without any concerns. You may use these implementations as a base for your own global scope implementation.

const {
	webScopeFactory,
	webworkerScopeFactory,
	nodeScopeFactory,
} = require('scoped-amd-library-plugin/globalFactories')

Security

You might be tempted to use this plugin to scope code from an untrusted source and so you can run in securely inside your own environment - DON'T!.

While you can theoretically map every single available global namespace of your environment using the ProvidePlugin in reality this "counter measure" can easily be worked around by malicious code - for example:

;(function () {
	return this
})()

This plugin was never designed for code sand-boxing. it's simply a way to separate dynamically imported bundles and their chunks into different scopes.

Providing an escape hatch

Sometimes you have no choice but to access the real global scope (such a case might be poly-filling general class constructors), while you can try and hack your way into accessing the global scope it's better to declare this access as a contact, accessing a predefined global namespace your consumer will connect to the real global object.

lib/webpack.config.js

module.exports = {
	//...
	plugins: [
		//...
		new ProvidePlugin({
			// wire global namespace use __global_escape_hatch__ from application code into the global dependency
			__global_escape_hatch__: [scopeDependencyName, __global_escape_hatch__],
		}),
	],
}

lib.js

// access global namespace from application code
const location = __global_escape_hatch__.location
// do somthing with location now retreived form the real global object of the consumer

consumer.js

// provide a global scope analog with the expected property refering to the real global scope
const scope = {
	__global_escape_hatch__: globalThis,
}

AMDLoader.load('lib.js', scope)

Caveats

web & webworker target un-scopable globals

When targeted for web / webworker environments, Webpack's runtime code require access to some globals that cannot be scoped due to the nature of how the runtime code act to register chunks. The globals are:

  • self - used in the runtime to write the webpackChunk global, chunk code will look up this global directly from self.
  • webpackChunk* - custom webpack set global used as a chunk registry and cache, usually suffixed by the project name

Contribute

Contributions are welcome!