鍍金池/ 問答/HTML/ vue異步路由webpack打包后的樣式加載問題(css異步加載問題?)

vue異步路由webpack打包后的樣式加載問題(css異步加載問題?)

我一共有五個頁面,采用了異步路由加載,后四個方式如下,這樣按需加載每個路由頁面,以免首屏加載過慢。

圖片描述

這個樣子,調(diào)試模式(dev)是沒有任何問題的,樣式能夠顯示出來,各種組件的樣式以style分開清晰顯示。

圖片描述

但是npm run build打包以后的文件就不行了,webpack并沒有將異步路由的vue的css文件給抽取出來,只抽取了用import方式引入組件的css,也就是index的css。

圖片描述

我后面將異步組件換成了import就能抽取樣式了。。。。

圖片描述

是不是我的css也應(yīng)該生成多個,而不是直接抽取到單個css?理論上點擊時應(yīng)更改css文件引入?
這算是webpack的build的配置有問題?畢竟dev沒啥毛病。。。后來又覺得是路由的問題,但是我webpack與vue都學(xué)藝不精,還是貼出來請大神看看,這個問題是vue-router能解決的,還是webpack能解決的,求個解決方案。

webpack.dev.conf.js

var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#cheap-module-eval-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    // new HtmlWebpackPlugin({
    //   filename: 'index.html',
    //   template: 'index.html',
    //   inject: true
    // }),
    new FriendlyErrorsPlugin()
  ].concat(utils.htmlPlugin())
})

webpack.prod.conf.js

var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    // new HtmlWebpackPlugin({
    //   filename: config.build.index,
    //   template: 'index.html',
    //   inject: true,
    //   minify: {
    //     removeComments: true,
    //     collapseWhitespace: true,
    //     removeAttributeQuotes: true
    //     // more options:
    //     // https://github.com/kangax/html-minifier#options-quick-reference
    //   },
    //   // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    //   chunksSortMode: 'dependency'
    // }),
    // split vendor js into its own file
    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']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ].concat(utils.htmlPlugin())
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
回答
編輯回答
伐木累

同樣遇到這個問題,解決了嗎?

2017年2月22日 23:54
編輯回答
執(zhí)念

您好,這個問題解決了嗎,我也遇到了這個問題

2018年4月24日 01:44
編輯回答
有你在

我的webpack是4.5.0,也碰到了這個問題,我只要一運行npm run dev馬上報錯Uncaught (in promise) TypeError: Cannot read property 'call' of undefined,而只要一熱刷新馬上就好了,找了半天是異步加載組件的時候只要import css就有這種問題,雖然我使用了extract-text-webpack-plugin@beta4.0.0,但是一直找不到解決辦法,直到我遇到了mini-css-extract-plugin,這應(yīng)該是webpack官方自己寫的支持webpack4的css分離插件,不妨嘗試一下,我的git項目地址webpack4初探,前端變化太快,準備回家種地了

2017年4月20日 04:21
編輯回答
笨小蛋

文件路徑出錯,webpack沒配置好

2018年7月26日 10:15
編輯回答
選擇

這還是只能式通過你的css寫法來區(qū)別吧,樣式不要覆蓋其他組件,單頁面css加載了就不能刪掉了。

2018年2月13日 20:07
編輯回答
喜歡你
new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      allChunks: true
    })
2017年6月6日 00:43