0.1.4 • Published 1 year ago

scoped-amd-library-plugin v0.1.4

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

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!

0.1.4

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago