簡體   English   中英

Parceljs / PostHTML - 防止 .htm 文件被重命名為 .html

[英]Parceljs / PostHTML - keeping .htm files from being renamed to .html

通過parcel .htm 文件構建時,輸出為.html 文件。 我更願意將 .htm 文件保留為輸出文件,但無法在 Parcel 或 Parcel 使用的 PostHTML 中找到一種方法。

我更新了一個舊的靜態網站以使用 Parcel 作為構建工具。 所有網站文件都帶有 .htm 文件擴展名。

我遇到了一個問題,當前包裹自動將所有 .htm 文件重命名為 .html,並自動將所有內部鏈接更新為 .html

這是目前的一個問題,因為該站點在搜索引擎上以 .htm 文件后綴編制索引,因此我目前需要保留兩個副本或為每個 .htm 文件執行重定向。

我不認為這是在parcel v2 中開箱即用的支持,但是使用自定義名稱插件可以相對輕松地完成

下面是一些可以工作的代碼:

import { Namer } from "@parcel/plugin";
import path from "path";

export default new Namer({
  name({ bundle }) {
    if (bundle.type === "html") {
      const filePath = bundle.getMainEntry()?.filePath;
      if (filePath) {
        let baseNameWithoutExtension = path.basename(filePath, path.extname(filePath));
        // See: https://parceljs.org/plugin-system/namer/#content-hashing
        if (!bundle.needsStableName) {
          baseNameWithoutExtension += "." + bundle.hashReference;
        }
        return `${baseNameWithoutExtension}.htm`;
      }
    }
    // Returning null means parcel will keep the name of non-html bundles the same.
    return null;
  },
});

將此插件與parcel 掛鈎而不發布單獨的包的最簡單方法是使用yarn 的鏈接協議

你可以這樣構建你的項目:

project
├── .parcelrc
├── package.json
├── src
│   └── index.html
└── parcel-namer-htm
    ├── package.json
    └── src
        └── HtmNamer.js <-- the code above

您的主要package.json將鏈接到您的parcel-namer-htm文件夾,如下所示:

{
  "name": "my-project",
  "dependencies": {
    "parcel": "^2.0.0",
    "parcel-namer-htm": "link:./parcel-transformer-foo"
  }
}

您的.parcelrc文件如下所示:

{
  "extends": "@parcel/config-default",
  "namers": ["parcel-namer-htm", "..."]
}

parcel-namer-htm/package.json將如下所示:

{
  "name": "parcel-namer-htm",
  "main": "src/HtmNamer.js",
  "engines": {
    "node": ">= 12.0.0",
    "parcel": "^2.0.0"
  },
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM