vue多页面项目配置

一直以来更多的是进行单页面开发。但在与其他同行的交流中,发现多页面项目也是业务的一种需求,趁着今天有时间,今天搞了一下。

多页面的配置,自然也可以根据路由的mode分为hash和history模式。

先说本人更熟悉的hash模式。

一,多页面要有多个入口

默认使用vue-cli 2初始化的项目,需要修改webpack的entry参数,修改两个入口,如下

// 原来
  entry: {
    app: ‘./src/main.js‘
  },
  // 修改后
  entry: {
    index: ‘./src/index/main.js‘,
    testp:‘./src/testp/main.js‘
  }

二,利用HtmlWebpackPlugin插件配置两个html文件。

// 文件1
    new HtmlWebpackPlugin({
      filename: ‘index.html‘,
      template: ‘./index.html‘,
      chunks: ["index"],
      minify: {
        removeComment: true,
        collapseWhitespace: true
      },
      inject: true
    }),
    // 文件2
    new HtmlWebpackPlugin({
      filename: ‘testp.html‘,
      template: ‘./testp.html‘,
      chunks: ["testp"],
      minify: {
        removeComment: true,
        collapseWhitespace: true
      },
      inject: true
    })

当然需要创建两个html,即index.html和testp.html。

三,改写配置文件webpack.dev.conf.js

devServer: {
    clientLogLevel: ‘warning‘,
    historyApiFallback: {
      rewrites: [
        // { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) },
        { from: /\/testp/, to: path.posix.join(config.dev.assetsPublicPath, ‘testp.html‘) },
      ],
    },
………………

这个是核心的。

最后hash模式下访问需要类似这样访问http://localhost:8080/testp/#/。

至于mode为history模式,在开发环境下基本一致,除了访问方式没有#。另外就是多页面的hash模式在生产环境下也需要后端配置的。

后续

如果是vue-cli3的项目,多页面配置使用的是参数pages,类似下面这种形式

pages: {
    ui: {
      // page 的入口
      entry: "src/views/index/main.js",
      // 模板来源
      template: "public/index.html",
      // 在 dist/index.html 的输出
      filename: "index.html",
      // 当使用 title 选项时,
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: "Index Page",
      // 在这个页面中包含的块,默认情况下会包含
      // 提取出来的通用 chunk 和 vendor chunk。
      chunks: ["chunk-vendors", "chunk-common", "ui"]
    },
    hh: {
      // page 的入口
      entry: "src/views/ui/main.js",
      // 模板来源
      template: "public/ui.html",
      // 在 dist/index.html 的输出
      filename: "ui.html",
      // 当使用 title 选项时,
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: "Index Page",
      // 在这个页面中包含的块,默认情况下会包含
      // 提取出来的通用 chunk 和 vendor chunk。
      chunks: ["chunk-vendors", "chunk-common", "hh"]
    },
……………………

相关推荐