使用Vue的默认webpack配置生成单个输出bundle.js

时间:2017-07-15 16:10:21

标签: webpack vue.js

我正在使用vue生成的webpack配置。这会在构建过程中向./dist/目录生成3个javascript文件:app.jsmanifest.jsvendor.js。所有这些文件都包含在index.html <script>中。如何配置webpack以仅生成包含所有这些内容的单个bundle.js

默认vue的webpack配置很大,所以我几乎无法理解那里发生了什么。我附在 webpack.base.conf.js 下面。如果您创建vue的应用程序,您将找到所有其他文件:npm install -g vue-clivue init webpack myapp(vue / router / eslink / karma / nightwatch单击否)。它们位于./build./config目录中。

var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

仅在您运行npm run build时才会出现这种情况吗?

如果是这样,文件webpack.prod.conf.js包含CommonsChunkPlugin:

 new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),

此外,拆分这样的代码最终会使您的网站更快,因为它不需要用户重新下载供应商文件(如果它们已经被缓存)