babel配置
babel版本升級到8.x以後發現出現了不少問題.
首先須要安裝webpack
"@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 配置以下web
{ 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 類型須要統一成一種,加這行代碼後就搞定,仍是能夠隨意用,並轉義成功.babel