【问题标题】:Parcel Bundler beautify, lint, and create .min.jsParcel Bundler 美化、lint 和创建 .min.js
【发布时间】:2023-03-17 08:35:01
【问题描述】:

我是使用 JS 进行自动化/测试/捆绑的新手,我大部分时间都设置了 parcel,但我注意到当它构建文件时,它实际上并没有使用 .min.js 部分保存它们文件名。我想知道是否有办法做到这一点而无需手动重命名构建文件。

我也在尝试找到一种方法让 parcel 浏览原始源文件(您正在处理的那些)并为我整理和美化它们

这是我的 package.json 的样子

{
  "name": "lpac",
  "version": "1.3.1",
  "description": "",
  "dependencies": {},
  "devDependencies": {
    "parcel": "^2.0.0-rc.0"
  },
  "scripts": {
    "watch": "parcel watch --no-hmr",
    "build": "parcel build"
  },
  "targets": {
    "lite-maps": {
      "source": ["./path/file1.js", "./path/file2.js", "./path/file3.js"],
      "distDir": "./path/build/"
    }
  },
  "browserslist": "> 0.5%, last 2 versions, not dead",
  "outputFormat" : "global",
}

我查看了文档,但找不到任何关于使用包裹进行棉绒或美化的内容。我该怎么做呢?如果您有这样做的教程链接,请也分享,因为除了基本的观看和构建文件之外,资源/教程似乎很少见

【问题讨论】:

  • 您的源文件(您正在处理的文件)是否以.min.js 为前缀,并且您希望在输出文件中通过包裹保留此扩展名?或者您是否希望包裹将.min 部分添加到输出文件(例如index.js(源)=> index.min.js(包裹输出))
  • @AndrewStegmaier 我希望它自动将.min.js 添加到文件名中,因为它可以很好地缩小它们,但是在构建后它们的名称相同我见过其他捆绑器,例如 webpack 和 rollup我认为在缩小文件后会自动将文件重命名为 .min.js/.min.css

标签: javascript lint parceljs


【解决方案1】:

不幸的是,没有开箱即用的设置可以导致包裹 javascript 输出看起来像 [fileName].[hash].min.js 而不是 [fileName].[hash].js.min.js 扩展名只是一种约定,以保持输出文件与源文件不同 - 它在运行时没有影响 - 而 parcel 的事实 automatic content hashing 很容易告诉这一点。即使它们没有.min.js 扩展名,这些输出文件肯定仍然是minified and optimized by default

但是,如果您真的非常想要这个,为包裹添加 Namer plugin 并在所有 javascript 输出中添加 .min.js 相对简单:

代码如下:

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

export default new Namer({
  name({ bundle }) {
    if (bundle.type === "js") {
      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}.min.js`;
      }
    }
    // Returning null means parcel will keep the name of non-js bundles the same.
    return null;
  },
});

然后,假设上述代码发布在一个名为 parcel-namer-js-min 的包中,您可以使用此 .parcelrc 将其添加到您的包裹管道中:

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

这里是an example repo where this is working

不幸的是,您的第二个问题的答案(“是否有一种方法可以让 parcel 遍历原始源文件(您正在处理的文件)并为我整理和美化它们”)。

但是,parcel 可以与执行此操作的其他命令行工具并排运行。例如,我的大部分项目都在package.json 中使用format 命令设置,如下所示:

{
   ...
   "scripts": {
      ...
      "format": "prettier --write src/**/* -u --no-error-on-unmatched-pattern"
   }
   ...
{

您可以使用husky 轻松使该命令自动运行以进行 git 提交和推送。

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2018-07-03
    • 1970-01-01
    • 2013-02-22
    • 2021-02-10
    • 1970-01-01
    • 2019-06-29
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多