js 兼容性處理


js 兼容性處理:babel-loader  @babel / core

npm install --save-dev babel-loader @babel/core

index.js 中,使用了箭頭函數的語法,打包編譯后同樣也是箭頭函數,這在 chrome中沒有任何問題,正常輸出7,但在 IE 中打開,會有語法錯誤,

 IE瀏覽器並不支持箭頭函數語法,所以需要 用 babel 做兼容性處理,webpack中就是 babel-loader

1,基本 js 兼容性 處理:@babel / preset-env,只能轉換基本語法,promise 高級語法不能轉換

npm install --save-dev  @babel/preset-env 

const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports={
    entry:'./src/index.js',
    output:{
        filename:'bundle.js',
        path:resolve(__dirname,'build')
    },
    module:{
        rules:[
            {
                test: /\.js$/,  //js兼容性處理,用到babel-loader @babel/core
                exclude:/node_modules/,
                loader:'babel-loader',
                options: {
                    presets: ['@babel/preset-env'] //預設:指示babel做怎么樣的兼容性處理(基本處理)
                }
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html'
        })
    ],
    mode:'development'
}

IE 中正常打印:

  

 處理后的 bundle.js中,const 變成了var,箭頭函數也變成了普通函數,將 es6以上的語法都處理為 es6以下的語法

    

 但不能解決 promise 等高級語法的兼容性問題:

 

 

2,全部 js 兼容性處理:@babel / polyfill,只要解決部分兼容性問題,卻要將所有兼容性代碼全部引入,體積太大

  npm install --save-dev  @babel/polyfill 

  直接在 index.js 中引入即可:

import '@babel/polyfill'
const add = (x, y) => {
  return x + y;
};
console.log(add(2, 5));

const p = new Promise((resolve,reject)=>{
  resolve('執行promise')
})
p.then(res=>{
  console.log(res)
})

  webpack編譯后,IE瀏覽器正常兼容 promise,但bundle.js 體積變化太大:

  

  

3,需要做兼容性處理的就做處理,按需加載,core-js

npm install --save-dev  core-js

const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports={
    entry:'./src/index.js',
    output:{
        filename:'bundle.js',
        path:resolve(__dirname,'build')
    },
    module:{
        rules:[
            {
                test: /\.js$/,  //js兼容性處理,用到babel-loader @babel/core
                exclude:/node_modules/,
                loader:'babel-loader',
                options: {
                    presets: [['@babel/preset-env', { //預設:指示babel做怎么樣的兼容性處理(基本處理)
                        useBuiltIns: 'usage',   // 按需加載
                        corejs: {  // 指定core-js版本
                            version: 3
                        },             
                        targets: { // 指定兼容性做到哪個版本瀏覽器
                            chrome: '60',
                            firefox: '60',
                            ie: '9',
                            safari: '10',
                            edge: '17'
                        }
                    }]] 
                
                }
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html'
        })
    ],
    mode:'development'
}

 打包后的文件輕了不少:

 

 

 

  

 


免責聲明!

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



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