我正在尝试有条件地使用require()模块,这些模块是vue组件,下面是代码片段,以便更好地理解
index.js
因此,我希望基于窗口url加载不同的组件(在使用django处理路由时不能使用vue-路由器)。
import Vue from 'vue'
const pathName = window.location.pathname
let components = []
if(pathName === '/page1/') {
components = require('./entry-point/page1.entry.js')
}
else if(pathName === '/page2/') {
components = require('./entry-point/page2.entry.js')
}
components.forEach(({ name, component }) => {
Vue.component(name, component)
})page1.entry.js
const ComponentA = require('../component-a.vue').default
const ComponentB = require('../component-b.vue').default
module.exports = [
{ name: 'component-a', component: ComponentA },
{ name: 'component-b', component: ComponentB }
]page2.entry.js
const ComponentC = require('../component-c.vue').default
module.exports = [
{ name: 'component-c', component: ComponentC }
]基本上,我正在尝试拆分代码,每次加载index.js时只加载所需的模块。这个应用程序不是一个典型的SSR (服务器端呈现),所以使用动态导入使用import()会造成问题。
上面的代码工作得很好,这里唯一的问题是,它真的加载了code-splitting或webpack所有的模块,即./entry-point/page1.entry.js和./entry-point/page2.entry.js?
所以,我的问题真的是,不是有条件地要求模块在上面的方式真的按照需要工作吗?或者webpack需要所有的模块()
发布于 2020-07-16 19:31:51
使用require不会使webpack拆分您的代码,最终您将得到一个巨大的包。只有动态导入才会有代码分裂。
此外,您还可以将组件加载到需要它的组件中,如果您没有在全局注册它们,您会更好。
https://stackoverflow.com/questions/62934607
复制相似问题