打包优化去掉console.log,webpack.js配置排除打包瘦身

JavaScript030

打包优化去掉console.log,webpack.js配置排除打包瘦身,第1张

在vue.config中,配置:

chainWebpack(config) {

    config.optimization.minimizer('terser').tap((args) =>{

      args[0].terserOptions.compress.drop_console = true

      return args

    })

}

通过配置vue-cli把一些平常不需要用的包排除在打包文件之外。

例如:让 webpack 不打包 vue xlsx 和 element 

先找到 vue.config.js , 添加 externals 项,具体如下:

再次运行打包,我们会发现包的大小已经大幅减小: 三个包已经不在打包的目标文件中了。

 但是我们还要使用这些包,可以通过CDN访问

在开发环境时,文件资源还是可以从本地node_modules中取出,而只有项目上线了,才需要去使用外部资源。此时我们可以使用 环境变量 来进行区分。具体如下:

在 vue.config.js 文件中:

let externals = {}

let cdn = { css: [], js: [] }

const isProduction = process.env.NODE_ENV === 'production' // 判断是否是生产环境

if (isProduction) {

  externals = {

      /**

      * externals 对象属性解析:

      * '包名' : '在项目中引入的名字'

    */

      'vue': 'Vue',

      'element-ui': 'ELEMENT',

      'xlsx': 'XLSX'

  }

  cdn = {

    css: [

      'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css 样式表

    ],

    js: [

      // vue must at first!

      'https://unpkg.com/[email protected]/dist/vue.js', // vuejs

      'https://unpkg.com/element-ui/lib/index.js', // element-ui js

      'https://cdn.jsdelivr.net/npm/[email protected]/dist/xlsx.full.min.js', // xlsx

    ]

  }

}

之后通过 html-webpack-plugin注入到 index.html之中:

chainWebpack(config) {

  config.plugin('preload').tap(() =>[

    {

      rel: 'preload',

      fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],

      include: 'initial'

    }

  ])

  // 注入cdn变量 (打包时会执行)

  config.plugin('html').tap(args =>{

    args[0].cdn = cdn // 配置cdn给插件

    return args

  })

  // 省略其他...

}

找到 public/index.html 通过配置CDN Config 依次注入 css 和 js。

修改head的内容如下:

<!-- 引入样式 -->

      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>

        <link rel="stylesheet" href="<%=css%>">

        <% } %>

    <!-- 引入JS -->

    <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>

      <script src="<%=js%>"></script>

    <% } %>

看官方描述:Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k. 就是去掉了ajax的功能。如果你不需要用到ajax或者使用了独立的第三方ajax库,就可以使用这个jquery.slim.js,这是个瘦身版,而不是什么插件。

它的思路是:3秒一次,把<li><a href="###"><b>春季番茄瘦身一周轻松减10斤! </b></a></li>这个添加到项中。直接点就是<li><a href="###"><b>春季番茄瘦身一周轻松减10斤! </b></a></li>这个项在末尾会出现很多次都是一样的,这就样不停的加上去