【问题标题】:Using conditional require() statements in JavaScript在 JavaScript 中使用条件 require() 语句
【发布时间】:2020-11-06 02:48:24
【问题描述】:

我正在尝试有条件地 require() 是 vue 组件的模块,下面的代码 sn-p 以便更好地理解

index.js

所以,我想根据窗口 url 加载不同的组件(不能使用 vue-router,因为路由是使用 django 处理的)

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 一开始就需要所有模块?

【问题讨论】:

标签: javascript vue.js webpack code-splitting


【解决方案1】:

使用 require 不会让 webpack 拆分你的代码,你最终会得到一个巨大的包。只有动态导入才会有代码拆分。

你也可以在需要的组件中加载你的组件,最好不要全局注册。

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 2023-01-28
    • 1970-01-01
    • 2012-05-03
    • 2017-03-31
    • 1970-01-01
    • 2011-09-25
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多