1. 程式人生 > >Node.js export default 使用require引入報錯:SyntaxError: Unexpected token export

Node.js export default 使用require引入報錯:SyntaxError: Unexpected token export

問題:

在a.js 中使用export default xxx 後,b.js使用require('a') 報錯:SyntaxError: Unexpected token export,只能使用import


解決辦法:

a中export default xxx改為 moudle.exports = xxxx

另外,如果在webpack中同一個模組下,使用了import xxx, 再使用module.exports也會出現報錯:

Uncaught TypeError: Cannot assign to read only property 'exports' of object

此時,需要把module.exports修改為export default。如果其他很多模組都使用require的方式引入本模組,那麼需要在require後面新增.default,或者使用一箇中間檔案複製本模組,然後在本模組require中間檔案,再使用module.exports匯出。