将 Vue 项目打包成一个可以嵌入 Ghost 博客的 js 文件 post

Bundle Vue project into single js file that can be embedded in Ghost blog post

我在 运行 yarn build 之后构建了一个简单的 Vue.js 项目。 dist 文件夹包含如下文件;

我想将所有文件(HTML、js、CSS)打包成一个可以嵌入到幽灵博客中的js文件post。

这是一个幽灵博客 post 的例子。

https://blog.openbloc.com/including-a-js-app-in-a-ghost-post/

我的问题是如何将我的 Vue.js 项目文件捆绑到一个可以部署在 ghost 博客中的文件中 post?

webpack 是正确的工具吗?我对其他选择持开放态度。

我正在使用@vue/cli 5.0.1,yarn v1.22.17

vue cli 对此有一个命令:https://cli.vuejs.org/guide/build-targets.html#library

您需要将此命令 --target lib 传递给 vue-cli-service build。这意味着您只需要一个最终文件。

此外,您还可以传递其他属性,例如:

  • --inline-vue,这将在您的包中包含 Vue,根据您的用例推荐什么;
  • --name,你的包文件名;
  • 在命令的末尾,您的应用程序的入口点,默认情况下是 src/Vue.js,但也可以是 main.js,例如。您必须根据您构建应用程序的方式进行测试;

因此,您可以尝试以下组合之一:

vue-cli-service build --target lib
vue-cli-service build --target lib --inline-vue
vue-cli-service build --target lib --inline-vue --name myApp
vue-cli-service build --target lib --inline-vue --name myApp src/main.js

创建单个 JS 文件输出

配置 Vue CLI 以输出单个 .js 文件:

  1. 使用 css.extract=false 禁用 CSS 提取。
  2. 使用 configureWebpack.optimization.splitChunks=false.
  3. 禁用 Webpack 的 chunk-splitting
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  ⋮
  css: {
    extract: false, 1️⃣
  },
  configureWebpack: {
    optimization: {
      splitChunks: false, 2️⃣
    },
  },
})

构建然后生成一个包含这些文件的 dist 目录:

dist/js/app.bd71ae48.js      # all app code, including template, scripts, and styles
dist/js/app.bd71ae48.js.map  # source map for development (optional)
dist/favicon.ico             # favicon shown in browser   (optional)
dist/index.html              # initial index              (optional)

Ghost 中的用法

  1. 在您的博客页面中,插入 custom HTML block
  1. 在 HTML 块中,添加一个 div,其 ID 与应用程序原始来源中 src/main.js 中的挂载点相匹配(默认 ID 为"app").

    <div id="app">Vue app loading...</div>
    
  2. 添加一个 <script> 以拉入先前构建的 app.js 文件。例如,如果您在 GitHub 上托管了脚本,您可以像这样使用 CDN link:

    <script src="https://cdn.jsdelivr.net/gh/tony19-sandbox/vue-cli-single-js-file@master/dist/js/app.bd71ae48.js"></script>
    
  3. 我注意到应用程序的 Vue 图标和标题未正确对齐(可能是由于继承的 Ghost 样式),因此通过在 HTML 块中添加 <style> 进行补偿 re-centers他们。

    <style>
    /* compensate for Ghost styles overriding the app's alignment */
    #app {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    </style>
    

结果如下所示:

GitHub

Ghost page