普通文組 2.5

在前端 React APP 專案中混用 ESM 與 CommonJS

總結

記錄一下如何設定 webpack 才能允許在專案中混用 EMS 與 CommonJS 的模組匯入、匯出語法 錯誤訊息:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

版本與環境

webpack: 5.64.4

筆記

ESM, CommonJS (Node.js)

  • ESM: import, export
  • CommonJS (Node.js): require, module.exports
  • ES6 modules are automatically strict-mode code, even if you don’t write "use strict"; in them. 模組內的程式碼一律預設為 strict mode

webpack 處理方式

  • 第 19 行:追加 sourceType: "unambiguous",

參考文件