1、webpack 配置:build/webpack.base.conf.js
module.export = { ... output: { path: config.build.assetsRoot, filename: '[name].js', chunkFilename: '[name].js',// 添加这一行 name 可以根据 webpackChunkName 注释友好定义 publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath },}
2、代码示例:
import 版本,可定义 webpackChunkName 注解,我喜欢
如果报错 import 方法不存在的话
cnpm install -D babel-plugin-syntax-dynamic-import//在.bablerc中引入syntax-dynamic-import插件{ "presets": ["es2015", "stage-3"], "plugins": ["syntax-dynamic-import"]}
import Vue from 'vue'import VueRouter from 'vue-router'// 页面组件 webpackChunkName 注释可以友好化分包的名称 需 webpack 2.4+// 使用 require + resolve 可以获得更好的通用性 但不支持 webpackChunkName 注解 用 id 做感觉可读性不好const componentMarket = () => import( /* webpackChunkName: "market" */ '@/components/Market');const componentCandy = () => import( /* webpackChunkName: "candy" */ '@/components/Candy');const componentWhiteBook = () => import( /* webpackChunkName: "white-book" */ '@/components/WhiteBook');const componentLogin = () => import( /* webpackChunkName: "login" */ '@/components/Auth/Login');const componentRegister = () => import( /* webpackChunkName: "register" */ '@/components/Auth/Register');Vue.use(VueRouter)const router = new VueRouter({ mode: 'history', routes: [{ path: '/', name: '/market', component: componentMarket }, { path: '/candy', name: '/candy', component: componentCandy }, { path: '/white-book', name: '/white-book', component: componentWhiteBook }, { path: '/login', name: '/login', component: componentLogin }, { path: '/register', name: '/register', component: componentRegister } ]})
resolve + require 版本,使用 id 做 chunkName
// import Market from '@/components/Market'// import Candy from '@/components/Candy'// import WhiteBook from '@/components/WhiteBook'// import Login from '@/components/Auth/Login'// import Register from '@/components/Auth/Register'import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)const router = new VueRouter({ mode: 'history', routes: [{ path: '/', name: '/market', component: resolve => require(['@/components/Market'], resolve) }, { path: '/candy', name: '/candy', component: resolve => require(['@/components/Candy'], resolve) }, { path: '/white-book', name: '/white-book', component: resolve => require(['@/components/WhiteBook'], resolve) }, { path: '/login', name: '/login', component: resolve => require(['@/components/Auth/Login'], resolve) }, { path: '/register', name: '/register', component: resolve => require(['@/components/Auth/Register'], resolve) } ]})router.beforeEach((to, from, next) => { console.log(to); console.log(from); next();})export default router;
就ok了