解決

これらのオプションは、モジュールの解決方法を変更します。Webpackは適切なデフォルト値を提供しますが、解決プロセスを詳細に変更することも可能です。リゾルバーの動作の詳細については、モジュール解決をご覧ください。

resolve

オブジェクト

モジュールの解決方法を構成します。たとえば、ES2015で`import 'lodash'`を呼び出す場合、`resolve`オプションはWebpackが`'lodash'`を探す場所を変更できます(`modules`を参照)。

webpack.config.js

module.exports = {
  //...
  resolve: {
    // configuration options
  },
};

resolve.alias

オブジェクト

特定のモジュールをより簡単に`import`または`require`するためのエイリアスを作成します。たとえば、一般的に使用される多くの`src/`フォルダにエイリアスを付けるには

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },
  },
};

このように相対パスを使用してインポートする代わりに

import Utility from '../../utilities/utility';

エイリアスを使用できます

import Utility from 'Utilities/utility';

与えられたオブジェクトのキーに末尾の`$`を追加して、完全一致を指定することもできます

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      xyz$: path.resolve(__dirname, 'path/to/file.js'),
    },
  },
};

これにより、次の結果が得られます

import Test1 from 'xyz'; // Exact match, so path/to/file.js is resolved and imported
import Test2 from 'xyz/file.js'; // Not an exact match, normal resolution takes place

次の表に、その他のケースについて説明します

aliasimport 'xyz'import 'xyz/file.js'
{}/abc/node_modules/xyz/index.js/abc/node_modules/xyz/file.js
{ xyz: '/abc/path/to/file.js' }/abc/path/to/file.jsエラー
{ xyz$: '/abc/path/to/file.js' }/abc/path/to/file.js/abc/node_modules/xyz/file.js
{ xyz: './dir/file.js' }/abc/dir/file.jsエラー
{ xyz$: './dir/file.js' }/abc/dir/file.js/abc/node_modules/xyz/file.js
{ xyz: '/some/dir' }/some/dir/index.js/some/dir/file.js
{ xyz$: '/some/dir' }/some/dir/index.js/abc/node_modules/xyz/file.js
{ xyz: './dir' }/abc/dir/index.js/abc/dir/file.js
{ xyz: 'modu' }/abc/node_modules/modu/index.js/abc/node_modules/modu/file.js
{ xyz$: 'modu' }/abc/node_modules/modu/index.js/abc/node_modules/xyz/file.js
{ xyz: 'modu/some/file.js' }/abc/node_modules/modu/some/file.jsエラー
{ xyz: 'modu/dir' }/abc/node_modules/modu/dir/index.js/abc/node_modules/modu/dir/file.js
{ xyz$: 'modu/dir' }/abc/node_modules/modu/dir/index.js/abc/node_modules/xyz/file.js

`package.json`で定義されている場合、`index.js`は別のファイルに解決される可能性があります。

`/abc/node_modules`は`node_modules`でも解決される可能性があります。

module.exports = {
  //...
  resolve: {
    alias: {
      _: [
        path.resolve(__dirname, 'src/utilities/'),
        path.resolve(__dirname, 'src/templates/'),
      ],
    },
  },
};

`resolve.alias`を`false`に設定すると、Webpackはモジュールを無視します。

module.exports = {
  //...
  resolve: {
    alias: {
      'ignored-module': false,
      './ignored-module': false,
    },
  },
};

resolve.aliasFields

[文字列]: ['browser']

この仕様に従って解析されるフィールド(`browser`など)を指定します。

webpack.config.js

module.exports = {
  //...
  resolve: {
    aliasFields: ['browser'],
  },
};

resolve.cacheWithContext

boolean

安全ではないキャッシュが有効になっている場合、キャッシュキーに`request.context`を含めます。このオプションは、`enhanced-resolve`モジュールによって考慮されます。resolveまたはresolveLoaderプラグインが提供されている場合、resolveキャッシングの`context`は無視されます。これにより、パフォーマンスの低下が解消されます。

resolve.conditionNames

string[]

パッケージのエントリポイントを定義する`exports`フィールドの条件名。

webpack.config.js

module.exports = {
  //...
  resolve: {
    conditionNames: ['require', 'node'],
  },
};

Webpackは、`resolve.conditionNames`配列にリストされているエクスポート条件に一致します。

`exports`フィールドのキーの順序は重要です。条件の照合中、前のエントリの方が優先順位が高く、後のエントリよりも優先されます。

例:

package.json

{
  "name": "foo",
  "exports": {
    ".": {
      "import": "./index-import.js",
      "require": "./index-require.js",
      "node": "./index-node.js"
    },
    "./bar": {
      "node": "./bar-node.js",
      "require": "./bar-require.js"
    },
    "./baz": {
      "import": "./baz-import.js",
      "node": "./baz-node.js"
    }
  }
}

webpack.config.js

module.exports = {
  //...
  resolve: {
    conditionNames: ['require', 'node'],
  },
};

インポート

  • `'foo'`は`'foo/index-require.js'`に解決されます
  • `'foo/bar'`は`'foo/bar-node.js'`に解決されます。条件付きエクスポートオブジェクトで`node`キーが`require`キーの前にあるためです。
  • `'foo/baz'`は`'foo/baz-node.js'`に解決されます

resolve.descriptionFiles

[文字列] = ['package.json']

説明に使用するJSONファイル。

webpack.config.js

module.exports = {
  //...
  resolve: {
    descriptionFiles: ['package.json'],
  },
};

resolve.enforceExtension

boolean = false

`true`の場合、拡張子なしのファイルは許可されません。そのため、デフォルトでは`require('./foo')`は`./foo`に`.js`拡張子が存在する場合に機能しますが、これを有効にすると`require('./foo.js')`のみが機能します。

webpack.config.js

module.exports = {
  //...
  resolve: {
    enforceExtension: false,
  },
};

resolve.extensionAlias

オブジェクト

拡張子を拡張子エイリアスにマッピングするオブジェクト。

webpack.config.js

module.exports = {
  //...
  resolve: {
    extensionAlias: {
      '.js': ['.ts', '.js'],
      '.mjs': ['.mts', '.mjs'],
    },
  },
};

resolve.extensions

[文字列] = ['.js', '.json', '.wasm']

これらの拡張子を順番に解決しようとします。複数のファイルが同じ名前を共有しているが拡張子が異なる場合、Webpackは配列に最初にリストされている拡張子を持つファイルを解決し、残りのファイルをスキップします。

webpack.config.js

module.exports = {
  //...
  resolve: {
    extensions: ['.js', '.json', '.wasm'],
  },
};

これにより、ユーザーはインポート時に拡張子を省略できます

import File from '../path/to/file';

上記のように`resolve.extensions`を使用すると、**デフォルトの配列が上書き**されることに注意してください。つまり、Webpackはデフォルトの拡張子を使用してモジュールを解決しようとしなくなります。ただし、`...'`を使用してデフォルトの拡張子にアクセスできます

module.exports = {
  //...
  resolve: {
    extensions: ['.ts', '...'],
  },
};

resolve.fallback

オブジェクト

通常の解決に失敗した場合に、モジュール要求をリダイレクトします。

webpack.config.js

module.exports = {
  //...
  resolve: {
    fallback: {
      abc: false, // do not include a polyfill for abc
      xyz: path.resolve(__dirname, 'path/to/file.js'), // include a polyfill for xyz
    },
  },
};

Webpack 5は、Node.jsのコアモジュールを自動的にポリフィルしなくなりました。つまり、ブラウザなどで実行されるコードでこれらを使用する場合は、npmから互換性のあるモジュールをインストールして自分で含める必要があります。Webpack 5より前にWebpackが使用していたポリフィルのリストを以下に示します。

module.exports = {
  //...
  resolve: {
    fallback: {
      assert: require.resolve('assert'),
      buffer: require.resolve('buffer'),
      console: require.resolve('console-browserify'),
      constants: require.resolve('constants-browserify'),
      crypto: require.resolve('crypto-browserify'),
      domain: require.resolve('domain-browser'),
      events: require.resolve('events'),
      http: require.resolve('stream-http'),
      https: require.resolve('https-browserify'),
      os: require.resolve('os-browserify/browser'),
      path: require.resolve('path-browserify'),
      punycode: require.resolve('punycode'),
      process: require.resolve('process/browser'),
      querystring: require.resolve('querystring-es3'),
      stream: require.resolve('stream-browserify'),
      string_decoder: require.resolve('string_decoder'),
      sys: require.resolve('util'),
      timers: require.resolve('timers-browserify'),
      tty: require.resolve('tty-browserify'),
      url: require.resolve('url'),
      util: require.resolve('util'),
      vm: require.resolve('vm-browserify'),
      zlib: require.resolve('browserify-zlib'),
    },
  },
};

resolve.mainFields

[文字列]

npmパッケージからインポートする場合(例:`import * as D3 from 'd3'`)、このオプションは、その`package.json`でチェックされるフィールドを決定します。デフォルト値は、Webpack構成で指定された`target`によって異なります。

`target`プロパティが`webworker`、`web`に設定されている場合、または指定されていない場合

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFields: ['browser', 'module', 'main'],
  },
};

その他のターゲット(`node`を含む)の場合

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFields: ['module', 'main'],
  },
};

たとえば、次のフィールドを含む`package.json`を持つ、`upstream`という任意のライブラリを考えてみましょう

{
  "browser": "build/upstream.js",
  "module": "index"
}

`import * as Upstream from 'upstream'`を呼び出すと、実際には`browser`プロパティのファイルに解決されます。`browser`プロパティは`mainFields`の最初の項目であるため、優先されます。一方、WebpackによってバンドルされたNode.jsアプリケーションは、最初に`module`フィールドのファイルを使用して解決しようとします。

resolve.mainFiles

[文字列] = ['index']

ディレクトリの解決に使用されるファイル名。

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFiles: ['index'],
  },
};

resolve.exportsFields

[文字列] = ['exports']

モジュール要求の解決に使用されるpackage.jsonのフィールド。package-exportsガイドラインで詳細を確認してください。

webpack.config.js

module.exports = {
  //...
  resolve: {
    exportsFields: ['exports', 'myCompanyExports'],
  },
};

resolve.modules

[文字列] = ['node_modules']

モジュールの解決時に検索するディレクトリをWebpackに指示します。

絶対パスと相対パスの両方を使用できますが、動作が少し異なることに注意してください。

相対パスは、Nodeが`node_modules`をスキャンする方法と同様に、現在のディレクトリとその祖先(つまり`./node_modules`、`../node_modules`など)を検索します。

絶対パスを使用すると、指定されたディレクトリのみが検索されます。

webpack.config.js

module.exports = {
  //...
  resolve: {
    modules: ['node_modules'],
  },
};

`node_modules/`よりも優先されるディレクトリを追加したい場合

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
  },
};

resolve.unsafeCache

`RegExp` `[RegExp]` `boolean: true`

モジュールの積極的だが**安全ではない**キャッシングを有効にします。`true`を渡すとすべてがキャッシュされます。

webpack.config.js

module.exports = {
  //...
  resolve: {
    unsafeCache: true,
  },
};

正規表現、または正規表現の配列を使用してファイルパスをテストし、特定のモジュールのみをキャッシュできます。たとえば、ユーティリティのみをキャッシュするには

webpack.config.js

module.exports = {
  //...
  resolve: {
    unsafeCache: /src\/utilities/,
  },
};

resolve.useSyncFileSystemCalls

boolean

リゾルバーに対して同期ファイルシステム呼び出しを使用します。

webpack.config.js

module.exports = {
  //...
  resolve: {
    useSyncFileSystemCalls: true,
  },
};

resolve.plugins

[Plugin]

適用する追加のresolveプラグインのリスト。これにより、`DirectoryNamedWebpackPlugin`などのプラグインを使用できます。

webpack.config.js

module.exports = {
  //...
  resolve: {
    plugins: [new DirectoryNamedWebpackPlugin()],
  },
};

resolve.preferRelative

boolean

有効にすると、Webpackは`node_modules`ディレクトリのモジュールを使用する代わりに、モジュール要求を相対要求として解決することを優先します。

webpack.config.js

module.exports = {
  //...
  resolve: {
    preferRelative: true,
  },
};

src/index.js

// let's say `src/logo.svg` exists
import logo1 from 'logo.svg'; // this is viable when `preferRelative` enabled
import logo2 from './logo.svg'; // otherwise you can only use relative path to resolve logo.svg

// `preferRelative` is enabled by default for `new URL()` case
const b = new URL('module/path', import.meta.url);
const a = new URL('./module/path', import.meta.url);

resolve.preferAbsolute

boolean

5.13.0+

`resolve.roots`への絶対パスを解決時に優先します。

webpack.config.js

module.exports = {
  //...
  resolve: {
    preferAbsolute: true,
  },
};

resolve.symlinks

boolean = true

シンボリックリンクをシンボリックリンクされた場所に解決するかどうか。

有効にすると、シンボリックリンクされたリソースは、シンボリックリンクされた場所ではなく、*実際の*パスに解決されます。これにより、パッケージをシンボリックリンクするツール(`npm link`など)を使用する場合、モジュール解決が失敗する可能性があります。

webpack.config.js

module.exports = {
  //...
  resolve: {
    symlinks: true,
  },
};

resolve.cachePredicate

function(module) => boolean

リクエストをキャッシュするかどうかを決定する関数。pathプロパティとrequestプロパティを持つオブジェクトが関数に渡されます。真偽値を返す必要があります。

webpack.config.js

module.exports = {
  //...
  resolve: {
    cachePredicate: (module) => {
      // additional logic
      return true;
    },
  },
};

resolve.restrictions

[文字列, 正規表現]

リクエストが解決されるパスを制限するための、解決制限のリスト。

webpack.config.js

module.exports = {
  //...
  resolve: {
    restrictions: [/\.(sass|scss|css)$/],
  },
};

resolve.roots

[文字列]

サーバー相対URL('/'で始まる)のリクエストが解決されるディレクトリのリスト。デフォルトはcontext設定オプションです。Windows以外のシステムでは、これらのリクエストはまず絶対パスとして解決されます。

webpack.config.js

const fixtures = path.resolve(__dirname, 'fixtures');
module.exports = {
  //...
  resolve: {
    roots: [__dirname, fixtures],
  },
};

resolve.importsFields

[文字列]

パッケージの内部リクエスト(#で始まるリクエストは内部とみなされます)を提供するために使用されるpackage.jsonからのフィールド。

webpack.config.js

module.exports = {
  //...
  resolve: {
    importsFields: ['browser', 'module', 'main'],
  },
};

resolve.byDependency

モジュールリクエストの種類ごとに解決オプションを設定します。

  • 型: [type: 文字列]: ResolveOptions

  • module.exports = {
      // ...
      resolve: {
        byDependency: {
          // ...
          esm: {
            mainFields: ['browser', 'module'],
          },
          commonjs: {
            aliasFields: ['browser'],
          },
          url: {
            preferRelative: true,
          },
        },
      },
    };

resolveLoader

オブジェクト { modules [文字列] = ['node_modules'], extensions [文字列] = ['.js', '.json'], mainFields [文字列] = ['loader', 'main']}

このオプションセットは上記のresolveプロパティセットと同一ですが、Webpackのローダーパッケージの解決のみに使用されます。

webpack.config.js

module.exports = {
  //...
  resolveLoader: {
    modules: ['node_modules'],
    extensions: ['.js', '.json'],
    mainFields: ['loader', 'main'],
  },
};

16 貢献者

sokraskipjackSpaceK33zpksjcesebastiandeutschtbroadleybyzyknumb86jgravoisEugeneHlushkoAghassimyshovanikethsahachenxsanjamesgeorge007snitin315