การ Build โปรเจค React (TypeScript)ให้ใช้ได้ใน Browser เวอร์ชันเก่า

wk
1 min readJan 22, 2020

--

ตัวอย่าง

ต้องการ Build โปรเจคต่อไปนี้ให้ใช้ได้กับ Google Chrome เวอร์ชัน 34

$ npm init
$ npm install --save-dev \
react react-dom \
@types/{react,react-dom} parcel-bundler

มีไฟล์ที่เกี่ยวข้อง คือ

  1. tsconfig.json

2. src/index.html

3. src/index.tsx

Build โปรเจคด้วย Parcel

$ npx parcel build src/index.html --out-dir web

ทดสอบโปรแกรมด้วย Google Chrome

พบว่าโปแกรมไม่สามารถทำงานได้ เนื่องจาก คลาส Map ยังไม่ Support ใน Chrome เวอร์ชัน 34

วิธีแก้

แก้โดยใช้ ts-polyfill ซึ่งเป็นการเพิ่ม Library ที่ Browser ยังไม่ Support ฝังเข้าไปในโปรแกรม โดยมีขั้นตอน ดังนี้

  • ติดตั้ง Polyfill ผ่าน npm
$ npm install --save-dev ts-polyfill
  • Import ts-polyfill ในไฟล์ src/index.tsx (บรรทัดแรก)
  • Build ด้วย Parcel
$ npx parcel build src/index.html --out-dir web
  • ทดสอบด้วย Google Chrome อีกครั้ง

จะเห็นว่าโปรแกรมแสดงคำว่า Hello, world! ตรงตามต้องการ โดยไม่มี Error สีแดงใน Console อีกแล้ว

--

--

No responses yet