Knowledge-Base icon indicating copy to clipboard operation
Knowledge-Base copied to clipboard

一个 vue-cli 项目编译生成多个子项目

Open Dream4ever opened this issue 7 years ago • 0 comments

资料汇总

搜索关键词:vue-cli multiple pages application


以下为旧版方案。

需求描述

用 vue-cli 生成多个页面,要放在各个不同的域名下,该如何实现呢?

方案调研

调研过程

Google vue-cli multiple dist folder,第一个链接 How to direct vue-cli to put built project files in different directories? 和自己的需求并不相关,讲的是如何把编译生成的 html 放到一个目录下,js、css 等静态资源文件放到另一个目录下。

再看第二个链接 How to create multiple vue apps in same folder,一看提问的内容,完全就是自己想要实现的需求嘛!很好。

一个回答说可以在 webpack 中设置 entryCopyWebpackPlugin 来实现需求:

module.exports = {
    entry: {
        App1: './App1/main.js',
        App2: './App2/main.js'
    },
    plugins: [
        new CleanWebpackPlugin(['dist'])
        , new CopyWebpackPlugin([
            { from: './App1/*.css' },
            { from: './App1/*.html' },
            { from: './App2/*.css' },
            { from: './App2/*.html' },
        ])
    ],

提问者在这个回答下面留言,说是在 Multiple entry points -> multiple html outputs? #218 中找到了解决办法。

同时提问者自己也单独补充了一个回答,给出了自己在用的方法,设置 webpack.prod.conf.js 中的 HtmlWebpackPlugin 插件:

new HtmlWebpackPlugin({
    filename: 'app1.html',
    template: 'app1_template.html',
    inject: true,
    chunks: ['app1', "vendor", "manifest"],
    chunksSortMode: 'dependency'
}),
new HtmlWebpackPlugin({
    filename: 'app2.html',
    template: 'app2_template.html',
    inject: true,
    chunks: ['app2', "vendor", "manifest"],
    chunksSortMode: 'dependency'
}),

入选方案

应用过程

为了保证能够按自己的需求生成多个 index.html,那么就需要先研究研究哪些地方会用到这个文件。

搜索新建的 vue-cli 项目的 buildconfig 文件夹,研究了一下用到 index.html 的文件,相关代码及功能整理如下:

// config\index.js
// 设置发布后的 `index.html` 的路径
module.exports = {
   ...
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
  }
}
// build\webpack.dev.conf.js

  // 设置开发模式下 historyApiFallback 的重写规则
  devServer: {
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },

  // 设置什么?
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
// build\webpack.prod.conf.js

  // 设置什么?
  // 这里 config.build.index 的值就是第一处用到 `index.html` 的代码
  plugins: [
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
    }),

此外,生成的页面都是放在网站的子目录下的,所以还需要设置静态资源相对于 index.html 的路径。

Dream4ever avatar Jun 13 '18 14:06 Dream4ever