webpack4.0 babel配置遇到的問題


babel配置
babel版本升級到8.x之后發現出現了很多問題.
首先需要安裝

"@babel/core": "^7.1.2",
"@babel/plugin-transform-object-assign": "^7.0.0",
"@babel/plugin-transform-runtime": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/runtime": "^7.1.2",
"babel-loader": "^8.0.4"

因為babel8.x插件依賴這些插件.
因為我的項目需要兼容IE8 所以我的babel-loader 配置如下

{
      test: /\.js$/,
      include: dirVars.srcRootDir,
      loader: 'babel-loader',
      options: {
        presets: [
          [
            "@babel/preset-env",
            {
              "targets": {
                "browsers": ["ie >= 8"]
              },
              //"useBuiltIns": 'usage',
              "modules": "commonjs"
            }
          ]
        ],
        cacheDirectory: true,
        plugins: [
          '@babel/plugin-transform-runtime', "@babel/plugin-transform-object-assign"
        ]
      }
    }

打包之后發現我的項目出錯了,因為項目里有個js用了Object.assign()方法 所有報這個方法的錯誤.
以前webpack3 配置babel plugins: ['transform-runtime'],當時babel版本6.x直接就會轉義這個方法.所以不會報錯.
現在babel8.x 配置babel plugins: ['@babel/plugin-transform-object-assign']無效報錯.
后來google后查找,發現了2種好的解決辦法
第一種辦法先安裝"@babel/polyfill": "^7.0.0",
babel-loader 加配置"useBuiltIns": 'usage'
"useBuiltIns": 'usage' 的意思是對應的環境自動替換為所需的 polyfill。
詳情看這篇文章https://juejin.im/entry/596309365188252ec3400aaf
這篇文章會介紹為什么不直接引入babel/polyfill.
第二種辦法用@babel/plugin-transform-object-assign插件.
配置完成后,運行demo並且報錯
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
網上解決方法如下:
點開錯誤的文件,標注錯誤的地方是這樣的一段代碼:
import {normalTime} from './timeFormat';
module.exports={
  normalTime
};
就是module.exports;
百度查不到,google一查果然有。
原因是:The code above is ok. You can mix require and export. You can‘t mix import and module.exports.
翻譯過來就是說,代碼沒毛病,在webpack打包的時候,可以在js文件中混用require和export。但是不能混用import 以及module.exports。
因為webpack 中不允許混用import和module.exports,
解決辦法就是統一改成ES6的方式編寫即可.
我的解決辦法:
babel-loder配置加一行代碼"modules": "commonjs"
這是因為這個配置環境下module 類型需要統一成一種,加這行代碼后就搞定,還是可以隨意用,並轉義成功.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM