Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีป้องกัน Moment.js ไม่ให้โหลด Locale ทั้งหมดด้วย Webpack

เมื่อ require('moment') และบандิล์ด้วย Webpack ขนาดไฟล์จะโตมาก เพราะ Moment.js รวมไฟล์ locale ทุกภาษาไว้ด้วย (ประมาณ 60+ locales)

วิธีแก้: ใช้ IgnorePlugin

const webpack = require('webpack');

module.exports = {
  plugins: [
    // ลองทุก locale files ของ moment.js
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    }),
  ],
};

หมายเหตุ: รูปแบบใหม่ของ Webpack 5 ใช้ object syntax แทน positional arguments

โหลด Locale เฉพาะที่ต้องการในโค้ด

const moment = require('moment');

// โหลด locale ภาษาญี่ปุ่นอย่างเดียว
require('moment/locale/ja');
moment.locale('ja');

console.log(moment().format('LLLL')); // 2024年1月15日 月曜日 10:30

วิธีอื่น: ใช้ moment-locales-webpack-plugin (แนะนำ)

const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

module.exports = {
  plugins: [
    new MomentLocalesPlugin({
      localesToKeep: ['ja', 'th', 'en-gb'], // ระบุ locale ที่ต้องการเก็บ
    }),
  ],
};

ตัวเลือกอื่น: ใช้ Day.js (Lightweight Alternative)

หากขนาดไฟล์สำคัญมาก พิจารณาย้ายไปใช้ Day.js (ขนาด ~2KB gzipped vs Moment ~20KB+)

import dayjs from 'dayjs';
import 'dayjs/locale/th';
import 'dayjs/locale/ja';

dayjs.locale('th');
console.log(dayjs().format('LLLL'));

สรุปผลกระทบต่อ Bundle Size

วิธีขนาดประมาณหมายเหตุ
Moment + ทุก Locale~70-100 KBค่าเริ่มต้น
Moment + IgnorePlugin + 1 Locale~15-20 KBลด ~80%
Moment + MomentLocalesPlugin~15-20 KBควบคุม locale ได้ง่าย
Day.js + Locale ที่ต้องการ~2-5 KBเล็กที่สุด API ใกล้เคียง Moment