详解Vue使用 Swiper 在 iOS 小于 11 时出现错误

前言

swiper这是一个很强大的轮播展示工具,但往往也会有一些未知BUG,尤其是在手机端,由于性能局限,会导致效果和PC测试的时候有完全不一样的效果

在H5项目中,需要用到翻页效果,通过 Swiper 来实现,安装 Swiper

npm install swiper --save-dev

但是实际使用中,发现低版本 iOS < 11 会出现下面这个错误:

SyntaxError: Unexpected keyword 'const'. Const declarations are not supported in strict mode

原因 

Swiper.js 这个 npm 包里面还使用了 dom7 和 ssr-window,所以需要对这两个插件进行 Babel 转 ES5

解决方案

Vue CLI 2.x 下,在 build/webpack.base.config.js 文件中修改

// ...
modules: {
  rules: [
  // ...
  {
    test: /.js$/,
    loader: 'babel-loader',
    include: [
      resolve('src'), 
      resolve('test'),
      resolve('node_modules/swiper/dist/js/'),
      resolve('node_modules/webpack-dev-server/client'),
      // 新增
      resolve('node_modules/swiper'),
      resolve('node_modules/dom7'),
      resolve('node_modules/ssr-window')
    ]
   },
  // ...
  ]
}
// ...

Vue CLI 3.x 下

在 vue.config.js 中增加 transpileDependencies 配置

module.exports = {
  transpileDependencies: [
    "swiper",
    "dom7",
    "ssr-window"
  ]
}

猜你喜欢

转载自blog.csdn.net/guoweifeng0012/article/details/90210611