vue.config.js 配置多入口文件

在 Vue CLI 项目中配置多入口文件主要是为了支持多页面应用的需求。通常情况下,一个 Vue CLI 项目默认只有一个入口文件 src/main.js,所有的功能和路由都基于这个入口文件展开。但是,对于一些大型应用或者需要独立部署的多个子应用来说,可能需要将不同的功能模块拆分成多个独立的 HTML 页面,每个页面都有自己的入口文件。

背景

在某些场景下,比如企业内部管理系统、复杂的单页应用(SPA)中需要支持多页面结构,或者需要将不同功能模块独立部署的情况下,使用多入口文件会更加合适。

好处

  1. 性能优化:

    • 减少初始加载时间:通过将应用分割成多个较小的页面,可以减少首次加载时需要下载的资源量。
    • 按需加载:用户访问特定页面时才加载该页面的资源,提高了用户体验。
  2. 代码组织:

    • 更清晰的代码结构:每个页面有独立的入口文件,使得代码更容易维护和理解。
    • 模块化开发:不同的团队可以并行开发不同的页面,提高开发效率。
  3. 部署灵活性:

    • 独立部署:不同的页面可以独立部署,不需要整个应用重新打包。
    • 多环境支持:可以在不同的环境中部署不同的页面版本。

示例:

在 vue.config.js 文件中配置多入口文件,可以按照下面的方式来进行

module.exports = {
  // 配置多页面入口
  pages: {
    index: { // 默认入口
      // page 的入口
      entry: 'src/index/main.js',
      // 模板来源
      template: 'public/index.html',
      // 在 dist/index.html 的输出
      filename: 'index.html',
      // 当使用 title 选项时,
      // template 中的 <title> 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page',
      // 片段注入到页面的地点,
      // 可以是 (head / end / body / top / bottom)
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    },
    otherpage: { // 新增的入口
      // page 的入口
      entry: 'src/otherpage/main.js',
      // 模板来源
      template: 'public/otherpage.html',  // 或者 'public/otherpage/otherpage.html'
      // 在 dist/otherpage.html 的输出
      filename: 'otherpage.html',
      // 当使用 title 选项时,
      // template 中的 <title> 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Other Page',
      // 片段注入到页面的地点,
      // 可以是 (head / end / body / top / bottom)
      chunks: ['chunk-vendors', 'chunk-common', 'otherpage']
    }
  }
}

在这个示例中,我们定义了两个入口页面:

  • index: 这是默认的入口页面,其配置可以省略。
  • otherpage: 这是我们新增的入口页面,它有自己的入口文件 src/otherpage/main.js 和模板文件 public/otherpage.html

文件目录如图:
在这里插入图片描述

确保在 src 目录下创建了一个名为 otherpage 的文件夹,并在其中放置 main.js 文件。同时,在 public 目录下创建一个名为 otherpage.html 的模板文件。

这样配置后,当你运行 npm run servenpm run build 命令时,将会生成两个 HTML 文件:index.htmlotherpage.html,每个文件都对应自己的入口文件和资源。

浏览器访问:

  • index.html 页面访问: http://localhost:8230/#/home
    在这里插入图片描述

  • otherpage.html 页面访问 http://localhost:8230/otherpage.html#/home
    在这里插入图片描述

public 中的 otherpage.htmlindex.html 同级目录 或者把 otherpage.html 放入 otherpage 文件夹里, 两者在浏览器里访问的地址都是 http://localhost:8230/otherpage.html#/home

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值