微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Github Pages build with vite

前言

为什么选 Vite {#why-vite} | Vite中文网 (vitejs.cn)

部署静态站点 {#deploying-a-static-site} | Vite中文网 (vitejs.cn)

一、开始 vite

开始 {#getting-started} | Vite中文网 (vitejs.cn)

搭建 Vite 项目

兼容性注意

Vite 需要 Node.js 版本 >= 12.0.0。

# npm 6.x
npm init vite@latest my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue

# 进入项目文件夹
cd my-vue-app

# 运行项目
npm run dev

# 打包项目
npm run build

# 预览打包项目
npm run preview

# yarn / pnpm 请移步官网

二、 部署静态站点

部署静态站点 {#deploying-a-static-site} | Vite中文网 (vitejs.cn)

这时候如果上传到 github 代码库后,配置完 Github Pages Setting 后,根据分配的链接已经可以导向到代码库中的 index.html 了。

如果出现路径错误,请继续往下看。

三、publish 脚本

'use strict';

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');

const packagePath = path.resolve(__dirname, '../package.json');
const indexPath = path.resolve(__dirname, '../dist/index.html');
const errorPath = path.resolve(__dirname, '../dist/404.html');
const packageData = JSON.parse(fs.readFileSync(packagePath));

// 获取原index.html文件内容
let indexContent = fs.readFileSync(indexPath, 'utf-8');
indexContent = indexContent
  .replace(
    '<Meta charset="utf-8" />',
    `<Meta charset="utf-8" />\n  <Meta name="version" content="V${
      packageData.version
    }">\n  <Meta name="name" content="${packageData.name}">\n  <Meta name="author" content="${
      packageData.author.name
    } || ${packageData.author.email}">\n  <Meta name="keyword" content="${packageData.keywords.join(
      ',',
    )}">\n  <Meta name="description" content="${packageData.description}">`,
  )
  .replace(/\/assets/g, `${packageData.author.url}/assets`);
// 写入模式打开index.html
const fd = fs.openSync(indexPath, 'w');
// 内容写入
fs.writeFile(fd, indexContent, 'utf8', function (writeErr) {
  if (!writeErr) {
    console.log(chalk.blue(`index.html 文件 Publish 成功!`));
    fs.closeSync(fd);
  } else {
    console.log(chalk.red(writeErr));
  }
});
// 同步更新404文件
const errorfd = fs.openSync(errorPath, 'w');
fs.writeFile(errorfd, indexContent, 'utf8', function (writeErr) {
  if (!writeErr) {
    console.log(chalk.blue(`404.html 文件 Synchronous update 成功!`));
    fs.closeSync(errorfd);
  } else {
    console.log(chalk.red(writeErr));
  }
});

以上是一个 js 的脚本,会读取已经 vite 打包完成后的 dist 文件夹中的 index.html 和 404.html(可以提前在 public 目录下创建一个空的 404.html 文件,或者改进此处的方法,使用 fs.mkdirsync 生成 404.html ) 以及 package.json 文件(具体路径请另行修改),使用 package.json 中的数据对页面进行标签以及静态资源引入的增补,package.json 内容如下

build 指令中添加上 publish 脚本的执行,&& 是指在前面的指令执行完成后再执行后面的语句。

将 index.html 的内容同步到 404.html 中原因:单页面应用是路由的变更,其实只是替换 index.html 中的部分元素,浏览器刷新后,github 会匹配对应路径下的 index.html 文件,找不到的话会指向 404.html 中。

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐