【问题标题】:Why do Vue single file components compile to such large files?Vue单文件组件为什么要编译成这么大的文件?
【发布时间】:2017-06-07 04:16:51
【问题描述】:

我是 Vue 和 Grunt/Gulp/Webpack 的新手。我有一个 Vue 应用程序可以正常工作(Grunt:browserify -> babel -> uglify),设置如下:

// app.js
const LoginComponent = require('./login.js')

// login.js
const template = `<some html>`
module.exports = Vue.component('login-component', {
    template: template,
    // component stuff
})

然后,为了让我的组件更具可读性,我切换到单文件组件(Webpack、Grunt: babel -> uglify),然后像这样工作:

// app.js
import LoginComponent from './login.js'

// login.js
<template>
    <some html>
</template>
<script>
export defalut {
    // component stuff
}
</script>

问题是使用 webpack 时文件大小翻了一番。第一个设置导致app.min.js3.3kb,第二个使用webpack 设置是7.0kb

这是正常现象还是我做错了什么?

我的webpack.config.js 看起来像这样:

var path = require('path')

module.exports = {
  entry: './resources/js/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'resources/js/temp')
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
    ]
  }
}

【问题讨论】:

  • 你为什么要使用 Grunt 顺便说一句?独立的 Webpack 应该够用了吧?
  • 当我使用 Webpack 时,我只将它用于导入/导出功能。我还没有看到如何使用 webpack 将 es6 转换为旧版 js 或缩小 js 文件。这就是我使用 Grunt 的原因,因为我知道它可以做这些事情。
  • 你可以使用babel loader来转换es5,uglify plugin,我可能会写一个答案
  • 只写那个答案,如果它也解决了我的问题:为什么我的第二种方法产生的 js 文件是第一种方法的两倍?

标签: javascript webpack gruntjs vue.js


【解决方案1】:

我看不出你的配置有什么问题,有时 webpack 需要生成一些运行时代码来解释你的包大小的增加。

但是,您可以通过使用DefinePluginNODE_ENV 变量设置为production 并利用UglifyjsWebpackPlugin 来减少它,这将导致优化的代码很可能更小,因此类似于以下内容

module.exports = {
  entry: './resources/js/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'resources/js/temp')
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') },
    }),
    new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }),
  ]
}

您还可以指定选项 dead_code 进行 uglify,以便删除从未使用过的代码,这可能对您的情况有所帮助。

此外,您应该使用 babel-loader 和适当的预设完全摆脱 Grunt。

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2017-08-30
    • 2011-07-14
    • 2012-02-07
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多