ProvidePlugin

2023-05-24 17:28 更新

Automatically load modules instead of having to ?import? or ?require? them everywhere.

new webpack.ProvidePlugin({
  identifier: 'module1',
  // ...
});

or

new webpack.ProvidePlugin({
  identifier: ['module1', 'property1'],
  // ...
});

默認情況下,模塊解析路徑為當前文件夾(?./**?)和 ?node_modules? 。

還可以指定完整路徑:

const path = require('path');

new webpack.ProvidePlugin({
  identifier: path.resolve(path.join(__dirname, 'src/module1')),
  // ...
});

每當在模塊中遇到標識符作為自由變量時,模塊都會自動加載,并將標識符填充為加載的模塊的導出(或?qū)傩?,以支持命名導出)?/p>

要導入ES2015模塊的默認導出,必須指定模塊的默認屬性。

Usage: jQuery

為了自動加載 ?jquery? ,我們可以將其公開的兩個變量指向相應的? node? 模塊:

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
});

然后在我們的任何源代碼中:

// in a module
$('#item'); // <= works
jQuery('#item'); // <= also works
// $ is automatically set to the exports of module "jquery"

Usage: jQuery with Angular 1

Angular尋找 ?window.jQuery? 以確定jQuery是否存在,請參見源代碼。

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery',
});

Usage: Lodash Map

new webpack.ProvidePlugin({
  _map: ['lodash', 'map'],
});

Usage: Vue.js

new webpack.ProvidePlugin({
  Vue: ['vue/dist/vue.esm.js', 'default'],
});


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號