ContextReplacementPlugin

يشير context إلى التعابير الديناميكية داخل import() أو require()، مثل require('./locale/' + name + '.json'). عندما يقرأ webpack هذا النوع من التعابير، فإنه يستنتج المجلد ('./locale/') وregular expression مثل (/^.*\.json$/). وبما أن قيمة name غير معروفة وقت التجميع، فسيضمّن webpack كل ملف مطابق كـ module داخل bundle.

يسمح لك ContextReplacementPlugin بتغيير المعلومات التي استنتجها webpack. توجد أكثر من طريقة لإعداد plugin:

الاستخدام

new webpack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentResource?: string,
  newContentRecursive?: boolean,
  newContentRegExp?: RegExp
)

إذا طابق المورد، أي المجلد، قيمة resourceRegExp، فسيستبدل plugin المورد الافتراضي أو قيمة recursive أو regular expression الناتج بالقيم newContentResource أو newContentRecursive أو newContextRegExp على الترتيب. إذا كانت newContentResource مسارًا نسبيًا، فسيُحل نسبة إلى المورد السابق.

هذا مثال صغير لتقييد modules التي تُستخدم:

new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /de|fr|hu/);

في هذا المثال، يُقيّد context الخاص بـ moment/locale ليقبل فقط الملفات المطابقة لـ /de|fr|hu/. لذلك لن تُضمّن إلا هذه locales (راجع هذه المشكلة لمزيد من التفاصيل).

Content Callback

new webpack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentCallback: (data) => void
);

تستقبل دالة newContentCallback كائن data من ContextModuleFactory، والمتوقع منها أن تستبدل خاصية request في الكائن الممرر.

باستخدام هذا callback نستطيع إعادة توجيه requests ديناميكيًا إلى موقع جديد:

new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
  if (!/\/moment\//.test(context.context)) return;

  Object.assign(context, {
    regExp: /^\.\/\w+/,
    request: "../../locale", // resolved relatively
  });
});

خيارات أخرى

يتوفر أيضًا المعاملان newContentResource وnewContentCreateContextMap:

new webpack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentResource: string,
  newContentCreateContextMap: object // mapping runtime-request (userRequest) to compile-time-request (request)
);

يمكن استخدام هذين المعاملين معًا لإعادة توجيه requests بطريقة أدق. يسمح لك newContentCreateContextMap بربط runtime requests مع compile-time requests داخل object:

new ContextReplacementPlugin(/selector/, "./folder", {
  "./request": "./request",
  "./other-request": "./new-request",
});
·تعديل هذه الصفحة
السابق ›
ContextExclusionPlugin
‹ التالي
DefinePlugin

1 مساهم

RlxChap2