--- tags: webpack, disqus: hackmd --- # webpack(5) 模組化js 答案來自:[webpack 新手教學之淺談模組化與 snowpack](https://blog.huli.tw/2020/01/21/webpack-newbie-tutorial/) Q:你知道 require/module.exports 與 import/export 的差別嗎? require/module.exports 是一套叫做 CommonJS 的規範,Node.js 有支援,瀏覽器沒有。 import/export 是 ES6 的規範,Node.js 部分支援,瀏覽器也是部分支援。 --- >**module.export配require = ES6以前的用法** >**export default配import = ES6的寫法** 這一段看起來跟上面的解答很有衝突,我打算透過實作測試一下來暸解。 但是還沒開始動手做測試。 --- ## module.export && require 首先在我們的src的js資料夾底下開一個beforeES6.js的檔案 ``` HTML= module.exports = { name: 'chris handsome' } 或者 module.exports = function(){ console.log('chris handsome'); } ``` 接著到你src的js資料夾下的index.js去require你的beforeES6.js的內容 在index.js裡打上這一段,然後run dev在本機看一下成果 ``` HTML= var beforeES6 = require('./beforeES6.js'); console.log(beforeES6); ``` ![](https://i.imgur.com/6fVmKFY.png) **當然也可以帶參數進去** beforeES6.js ``` HTML= module.exports = function(name){ console.log(name + ' = handsome'); } ``` index.js ``` HTML= var beforeES6 = require('./beforeES6.js'); beforeES6('chris'); ``` ![](https://i.imgur.com/zQoAuoR.png) --- ## export default && import 首先一樣先在src底下的js資料夾建立一支afterES6.js的檔案 ``` HTML= export default { name: 'chris YES' } ``` 然後到src底下的js資料夾的index.js,然後輸入下面那段 ``` HTML= import afterES6 from './afterES6.js' console.log(afterES6); ``` ![](https://i.imgur.com/UEuqFnn.png) 成功 --- ## 注意事項 如果在寫JS的時候<span style="color: red">沒有用ES6</span>的語法,那可以不用載入babel-loader 相對的如果有用es6在開發,就要記得使用babel-loader 最後webpack.config.js裡的module.exports是<span style="color: red">不能改成</span>export default的 因為node.js還沒有支援ES6的引入跟匯出