• Stars
    star
    897
  • Rank 48,909 (Top 1.0 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Offers an async require.resolve function. It's highly configurable.

enhanced-resolve

npm Build Status codecov Install Size GitHub Discussions

Offers an async require.resolve function. It's highly configurable.

Features

  • plugin system
  • provide a custom filesystem
  • sync and async node.js filesystems included

Getting Started

Install

# npm
npm install enhanced-resolve
# or Yarn
yarn add enhanced-resolve

Resolve

There is a Node.js API which allows to resolve requests according to the Node.js resolving rules. Sync and async APIs are offered. A create method allows to create a custom resolve function.

const resolve = require("enhanced-resolve");

resolve("/some/path/to/folder", "module/dir", (err, result) => {
	result; // === "/some/path/node_modules/module/dir/index.js"
});

resolve.sync("/some/path/to/folder", "../../dir");
// === "/some/path/dir/index.js"

const myResolve = resolve.create({
	// or resolve.create.sync
	extensions: [".ts", ".js"]
	// see more options below
});

myResolve("/some/path/to/folder", "ts-module", (err, result) => {
	result; // === "/some/node_modules/ts-module/index.ts"
});

Creating a Resolver

The easiest way to create a resolver is to use the createResolver function on ResolveFactory, along with one of the supplied File System implementations.

const fs = require("fs");
const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve");

// create a resolver
const myResolver = ResolverFactory.createResolver({
	// Typical usage will consume the `fs` + `CachedInputFileSystem`, which wraps Node.js `fs` to add caching.
	fileSystem: new CachedInputFileSystem(fs, 4000),
	extensions: [".js", ".json"]
	/* any other resolver options here. Options/defaults can be seen below */
});

// resolve a file with the new resolver
const context = {};
const lookupStartPath = "/Users/webpack/some/root/dir";
const request = "./path/to-look-up.js";
const resolveContext = {};
myResolver.resolve(context, lookupStartPath, request, resolveContext, (
	err /*Error*/,
	filepath /*string*/
) => {
	// Do something with the path
});

Resolver Options

Field Default Description
alias [] A list of module alias configurations or an object which maps key to value
aliasFields [] A list of alias fields in description files
extensionAlias {} An object which maps extension to extension aliases
cachePredicate function() { return true }; A function which decides whether a request should be cached or not. An object is passed to the function with path and request properties.
cacheWithContext true If unsafe cache is enabled, includes request.context in the cache key
conditionNames [] A list of exports field condition names
descriptionFiles ["package.json"] A list of description files to read from
enforceExtension false Enforce that a extension from extensions must be used
exportsFields ["exports"] A list of exports fields in description files
extensions [".js", ".json", ".node"] A list of extensions which should be tried for files
fallback [] Same as alias, but only used if default resolving fails
fileSystem The file system which should be used
fullySpecified false Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests)
mainFields ["main"] A list of main fields in description files
mainFiles ["index"] A list of main files in directories
modules ["node_modules"] A list of directories to resolve modules from, can be absolute path or folder name
plugins [] A list of additional resolve plugins which should be applied
resolver undefined A prepared Resolver to which the plugins are attached
resolveToContext false Resolve to a context instead of a file
preferRelative false Prefer to resolve module requests as relative request and fallback to resolving as module
preferAbsolute false Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots
restrictions [] A list of resolve restrictions
roots [] A list of root paths
symlinks true Whether to resolve symlinks to their symlinked location
unsafeCache false Use this cache object to unsafely cache the successful requests

Plugins

Similar to webpack, the core of enhanced-resolve functionality is implemented as individual plugins that are executed using tapable. These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved.

A plugin should be a class (or its ES5 equivalent) with an apply method. The apply method will receive a resolver instance, that can be used to hook in to the event system.

Plugin Boilerplate

class MyResolverPlugin {
	constructor(source, target) {
		this.source = source;
		this.target = target;
	}

	apply(resolver) {
		const target = resolver.ensureHook(this.target);
		resolver
			.getHook(this.source)
			.tapAsync("MyResolverPlugin", (request, resolveContext, callback) => {
				// Any logic you need to create a new `request` can go here
				resolver.doResolve(target, request, null, resolveContext, callback);
			});
	}
}

Plugins are executed in a pipeline, and register which event they should be executed before/after. In the example above, source is the name of the event that starts the pipeline, and target is what event this plugin should fire, which is what continues the execution of the pipeline. For an example of how these different plugin events create a chain, see lib/ResolverFactory.js, in the //// pipeline //// section.

Escaping

It's allowed to escape # as \0# to avoid parsing it as fragment.

enhanced-resolve will try to resolve requests containing # as path and as fragment, so it will automatically figure out if ./some#thing means .../some.js#thing or .../some#thing.js. When a # is resolved as path it will be escaped in the result. Here: .../some\0#thing.js.

Tests

yarn test

Passing options from webpack

If you are using webpack, and you want to pass custom options to enhanced-resolve, the options are passed from the resolve key of your webpack configuration e.g.:

resolve: {
  extensions: ['.js', '.jsx'],
  modules: [path.resolve(__dirname, 'src'), 'node_modules'],
  plugins: [new DirectoryNamedWebpackPlugin()]
  ...
},

License

Copyright (c) 2012-2019 JS Foundation and other contributors

MIT (http://www.opensource.org/licenses/mit-license.php)

More Repositories

1

webpack

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
JavaScript
64,061
star
2

webpack-dev-server

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.
JavaScript
7,728
star
3

tapable

Just a little module for plugins.
JavaScript
3,668
star
4

webpack-cli

Webpack's Command Line Interface
JavaScript
2,538
star
5

webpack-dev-middleware

A development middleware for webpack
JavaScript
2,468
star
6

react-starter

[OUTDATED] Starter template for React with webpack. Doesn't focus on simplicity! NOT FOR BEGINNERS!
JavaScript
2,215
star
7

webpack.js.org

Repository for webpack documentation and more!
MDX
2,197
star
8

docs

[OLD] documentation for webpack
JavaScript
1,456
star
9

memory-fs

[DEPRECATED use memfs instead] A simple in-memory filesystem. Holds data in a javascript object.
JavaScript
882
star
10

analyse

analyse web app for webpack stats
JavaScript
873
star
11

webpack-pwa

Example for a super simple PWA with webpack.
JavaScript
809
star
12

loader-utils

utils for webpack loaders
JavaScript
764
star
13

react-webpack-server-side-example

Example of an react application with webpack including server-side rendering.
JavaScript
460
star
14

node-libs-browser

[DEPRECATED] The node core libs for in browser usage.
JavaScript
445
star
15

watchpack

Wrapper library for directory and file watching.
JavaScript
373
star
16

webpack-with-common-libs

webpack with some common libraries
JavaScript
340
star
17

loader-runner

Runs (webpack) loaders
JavaScript
291
star
18

webpack-sources

Source code handling classes for webpack
JavaScript
254
star
19

changelog-v5

Temporary repo for the changelog for webpack 5
252
star
20

schema-utils

Options Validation
JavaScript
234
star
21

meeting-notes

Webpack core team meeting notes.
188
star
22

concord

[WIP] concord modules specification
156
star
23

example-app

[OUTDATED] example web app for webpack
JavaScript
139
star
24

fastparse

A very simple and stupid parser, based on a statemachine and regular expressions.
JavaScript
65
star
25

enhanced-require

[CURRENTLY UNMAINTAINED] Enhance the require function in node.js with support for loaders which preprocess files. This is a standalone polyfill for features of webpack.
JavaScript
64
star
26

playground

In-browser playground for webpack
JavaScript
59
star
27

analyse-tool

A tool to analyse your webpack build result. It allows to browse the compilation and points out options to optimize the build.
JavaScript
55
star
28

hot-node-example

Example for HMR in a node.js process
JavaScript
54
star
29

source-list-map

Fast line to line SourceMap generator.
JavaScript
39
star
30

benchmark

Run benchmarks for webpack.
JavaScript
37
star
31

core

[OBSOLETE in webpack 2] The core of webpack and enhanced-require...
JavaScript
26
star
32

media

23
star
33

voting-app

An application for casting votes on new webpack features and fixes.
JavaScript
22
star
34

tooling

A collection of reusable tooling for webpack repos.
JavaScript
20
star
35

graph

[DEPRECATED] Converts JSON stats from webpack to a nice SVG-Image.
JavaScript
13
star
36

template

[DEPRECATED] Create a new web app from a template.
JavaScript
10
star
37

webpack.github.com

webpack.github.com
JavaScript
10
star
38

management

Mission, Goals, projects and budget for webpack
6
star
39

github-org-overview

Scans all repos of a github organization and check if published
JavaScript
5
star
40

the-big-test

[OUTDATED] the big webpack/enhanced-require test
JavaScript
5
star
41

meetup-2018-05-08

QA for the webpack meetup in Munich
4
star
42

v4.webpack.js.org

Hosting for old version of webpack documentation
3
star
43

jquery-wpt-module

[DEPRECATED] webpack-template-module for jquery
JavaScript
2
star
44

bootstrap-wpt-module

[DEPRECATED] webpack-template-module for twitter's bootstrap
JavaScript
2
star
45

github-wiki

The server-side code (heruko) for serving the wiki as gh-pages.
JavaScript
2
star
46

enhanced-resolve-completion-demo

[OUTDATED] demo for the request completion of enhanced-resolve
JavaScript
2
star
47

webpack-tests-example

DEPRECATED (use mocha-loader now): A simple example for doing tests with webpack and mocha.
JavaScript
2
star