javascript - webpack require.ensure 代码分割问题

查看:139
本文介绍了javascript - webpack require.ensure 代码分割问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

require.ensure()引入的多个模块,打包后为什么会把所有使用require.ensure()的模块都打成包成一个文件了?
具体如下:

  1. app.js

  2. home.js(它里面已经包括了home.js和about.js的代码)

  3. vendors

我希望打包后require.ensure()加载的文件能分别输出,
如:

  1. home.js

  2. about.js

webpack如下(片段):

    //静态资源地址
    baseConfig.output.publicPath = '/assets/';
    baseConfig.output.filename = '[name].[chunkhash:8].js';
    baseConfig.output.chunkFilename = '[name].[chunkhash:8].js';
    
    let config = Object.assign({}, baseConfig, {
      entry: {
        vendors : ['core-js', 'react', 'react-dom', 'react-router', 'react-cookie', 'react-tap-event-plugin', 'whatwg-fetch'], //抽公共库
        app : path.join(__dirname, '../src/index')
      },
      cache: true,
      devtool : null,
      plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendors','[name].[chunkhash:8].js'),
        new ExtractTextPlugin('styles.[chunkhash:8].css',{allChunks: true}),
        new WebpackMd5Hash()
        ]
    });

代码结构如下:

  • rootRoute.js

    const rootRoute = {
      component: 'div',
      childRoutes: [ {
        path: '/',
        component: require('components/Main'),
        childRoutes: [
          require('./homeRoute'),
          require('./aboutRoute')
        ]
      } ]
    }
    module.exports = rootRoute;

  • homeRoute.js

    module.exports = {
      path: 'home',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          cb(null, require('components/Home'))
        }, 'home')
      }
    }

  • aboutRoute.js

    module.exports = {
      path: 'about',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          cb(null, require('components/About'))
        }, 'about')
      }
    }

  • components/home.js

import React, { PropTypes } from 'react'
const Home = React.createClass({
  render () {
    return (
      <div>
        <h1>Home</h1>
      </div>
    )
  }
})
module.exports = Home

  • components/about.js

import React, { PropTypes } from 'react'
const About = React.createClass({
  render () {
    return (
      <div>
        <h1>About</h1>
      </div>
    )
  }
})
module.exports = About

解决方案

自己找到问题所在了,原来webpack里有加载了这个plugin:
new webpack.optimize.AggressiveMergingPlugin()
查了一下文档,原来就是它把所有的chunkFile又合到一起了。

这篇关于javascript - webpack require.ensure 代码分割问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆