Git Product home page Git Product logo

parcel-namer-rewrite's Introduction

This plugin allows to rewrite bundle file names.

Why?

To get more control over bundle file names. You may find another useful plugin - https://github.com/ol-loginov/parcel-reporter-entries to get report about actual bundle file names.

Install and usage

Install the package first:

npm install --save-dev parcel-namer-rewrite

And edit .parcelrc file to add new namer (put it before or instead default one):

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

Configuration

Plugin takes all config from package.json file. Example of config is below:

/* package.json */
{
  "name": "...",
  "version": "...",
  "description": "",
  "parcel-namer-rewrite": {
    /* This is optional, you may omit that line, and default namer will be used to get actual names */
    "chain": "@parcel/namer-default",
    /* You may select between always|never hashing. See below for details*/
    "hashing": "always",
    /* Turn plugin on and off */
    "disable": false,
    /* Rewrite rules */
    "rules": {
      "styles/(.*).css": "$1.{hash}.css",
      "scripts/TestMePlease.js": "Dunno.js"
    },
    /* profiles are optional */
    "profiles": {
      "development": {
        /* for development Node mode */
      },
      "production": {
        /* for production Node mode */
      },
      "other-custom-profile": {
        /* this profile is activated via environment variable */
      }
    }
  }
}

This example:

  1. Rewrites all .css bundles in "styles" folder of distDir directly to distDir and adds hashes to names.
  2. Moves "scripts/TestMePlease.js" to "Dunno.js"

How to write rules

"rules" is the object with rules: "key" is RegExp pattern to search in file names, "value" is replacement strings (you may use RegExp references here)

Using hash in file names

File name "$1.{hash}.css" adds hash before extension. If hash is empty (in development mode, for example), then you get double dot in file name:

"file.{hash}.css" -> "file..css"

But there is a solution - just put dot inside brackets. For example: "file{.hash}.css" or "file{hash.}.css". In this case for empty hash strings all inside brackets will be removed. And you may use any single character instead of dot: "file{~hash}.css", "file{-hash}.css" are valid replacements.

Hashing mode

In development mode hashes are blank for file names. You may force hashing in development mode by setting "hashing" to true in "development" profile.

Like this:

/* package.json */
{
  "parcel-namer-rewrite": {
    "rules": {
      /* some rules  */
    },
    "profiles": {
      "development": {
        "hashing": "always"
      }
    }
  }
}

You may turn off hashing completely (even for non-entry bundles) by selecting hashing to "never". You may set it on the main configuration or in profile configuration.

Any other (or absent) value for `hashing' will keep hash only for assets that are hashed by parcel itself.

Hide logs

This plugin will log every renamed file. To disable this feature, add this option to package.json :

/* package.json */
{
  "parcel-namer-rewrite": {
    // ...
    "silent": true
  }
}

Disable in development mode

You may want to disable the namer in development mode. To disable the plugin, add this option to package.json profile "development" :

/* package.json */
{
  "parcel-namer-rewrite": {
    // ...
    "profiles": {
      "development": {
        "disable": true
      }
    },
  }
}

Configuration profiles

You may want to override some configuration based on some condition - use configuration profile feature! "profiles" section in plugin configuration may contain additional configuration options that are activated based on profile key. By default, there are "development" and "production" profiles (you don't need to activate it via environment). These profiles are being activated by current Node mode - development or production.

In configuration below plugin is turned off for production mode:

/* package.json */
{
  "parcel-namer-rewrite": {
    "profiles": {
      "development": {
        /* for development Node mode */
      },
      "production": {
        /* for production Node mode */
        "disable": true
      },
    }
  }
}

To activate other profiles - use environment variable PARCEL_NAMER_REWRITE_PROFILE. Here you may see command line:

PARCEL_NAMER_REWRITE_PROFILE=myprofile parcel build

and corresponding configuration profile in package.json (it disables hashing completely)

/* package.json */
{
  "parcel-namer-rewrite": {
    "profiles": {
      "myprofile": {
        "hashing": "never"
      }
    }
  }
}

You may activate multiple profiles with comma-delimited list of profile keys

PARCEL_NAMER_REWRITE_PROFILE=myprofile,profile2,profile3 parcel build

parcel-namer-rewrite's People

Contributors

ol-loginov avatar zouloux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

parcel-namer-rewrite's Issues

The "from" argument must be of type string. Received undefined

๐Ÿ› bug report

When starting Parcel 2 with plugin parcel-namer-rewrite connected to the project building, an error occurs: parcel-namer-rewrite: The "from" argument must be of type string. Received undefined

How to resolve this build error?

yarn build
$ parcel build templates/layouts/index.pug --dist-dir ./build
๐Ÿšจ Build failed.
parcel-namer-rewrite: The "from" argument must be of type string. Received undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "from" argument must be of type string. Received undefined
    at validateString (internal/validators.js:124:11)
    at Object.relative (path.js:1053:5)
    at nameFromContent (/Users/andrew/Sites/main-site/src/client/node_modules/@parcel/namer-default/lib/DefaultNamer.js:140:49)
    at Object.name (/Users/andrew/Sites/main-site/src/client/node_modules/@parcel/namer-default/lib/DefaultNamer.js:117:16)
    at Object.name (/Users/andrew/Sites/main-site/src/client/node_modules/parcel-namer-rewrite/lib/Namer.js:32:47)
    at BundlerRunner.nameBundle (/Users/andrew/Sites/main-site/src/client/node_modules/@parcel/core/lib/BundlerRunner.js:181:39)
    at /Users/andrew/Sites/main-site/src/client/node_modules/@parcel/core/lib/BundlerRunner.js:169:50
    at Array.map (<anonymous>)
    at BundlerRunner.nameBundles (/Users/andrew/Sites/main-site/src/client/node_modules/@parcel/core/lib/BundlerRunner.js:169:31)
    at async BundlerRunner.bundle (/Users/andrew/Sites/main-site/src/client/node_modules/@parcel/core/lib/BundlerRunner.js:134:5)
parcel-namer-rewrite: Rewrite styles.HASHREFb72dc01010dd39338f4bc3b150ae71dd.css -> styles.css
parcel-namer-rewrite: Rewrite styles.HASHREFc3920eb8ad6d86c5bb3b08894fe854c3.css -> styles.css
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
MacBook-Pro-Andrey:client andrew$

๐ŸŽ› Configuration (package.json, .parcelrc)

package.json

{
    "name": "main-site",
    "engines": {
        "node": "14"
    },
    "isLibrary": false,
    "targets": {
        "legacy": {
            "engines": {
                "browsers": [
                    ">= 0.25%",
                    "maintained node versions"
                ]
            },
            "isLibrary": false,
            "minify": false
        },
        "modern": {
            "engines": {
                "browsers": [
                    "defaults",
                    "not IE 11",
                    "maintained node versions"
                ]
            },
            "isLibrary": false,
            "minify": false
        }
    },
    "parcel-namer-rewrite": {
        "rules": {
            "styles(.*).css": "styles.css"
        }
    },
    "scripts": {
        "serve": "parcel serve templates/layouts/index.pug",
        "build": "parcel build templates/layouts/index.pug --dist-dir ./build"
    }
}

.parcelrc

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

๐Ÿค” Expected Behavior

The build should pass successfully without errors and crashes.
Files build/legacy/styles{~hash}.css and build/modern/styles{~hash}.css should have the output without hash in the names

As we can see the files started to be renamed as expected, but the build folder was never created due to a build error

parcel-namer-rewrite: Rewrite styles.HASHREFb72dc01010dd39338f4bc3b150ae71dd.css -> styles.css
parcel-namer-rewrite: Rewrite styles.HASHREFc3920eb8ad6d86c5bb3b08894fe854c3.css -> styles.css

๐Ÿ˜ฏ Current Behavior

Due to a build error with the connected parcel-namer-rewrite plugin - the distribution folders build/legacy/ and build/modern/ with the point-renamed files styles.css without hashes in the names was never created

๐Ÿ”ฆ Context

In my case, after Parcel 2 has build the assets, the builded ready-to-use bundles should work in the WordPress engine, which mainly needs static paths to the sources, that is why the hash should not be present in the bundle name.

For example: instead of a point to WordPress a file named
โŒ build/legacy/styles.a621ca41.css
we should point
โœ… build/legacy/styles.css

๐Ÿ’ป Code Sample

index.pug

block index
    doctype html
    html(lang='en')
        head
        meta(charset='UTF-8')
        meta(name='viewport' content='width=device-width initial-scale=1.0')
        meta(http-equiv='X-UA-Compatible' content='ie=edge')
        title Main Site

        link(rel='stylesheet' href='../../assets/styles/index.scss')

        body
            | Lorem, ipsum dolor.

๐ŸŒ Your Environment

Software Version(s)
Parcel 2.0.0-beta.1
Node v14.15.3
npm/Yarn 6.14.9/1.19.0
Operating System macOS Catalina 10.15.7
Note: The code above has been truncated to make it more informative, compact, and easier to read. This means that such fields as devDependencies are removed.

Add some examples to the readme

Thanks for the nice and simple plugin. I never got the parcel-reporter-entries plugin to work, so I didn't get to test this plugin for a long time. Maybe you should add some real world examples to the readme. The following rules help me to structure the dist folder::

  "parcel-namer-rewrite": {
    "rules": {
      "(.*)\\.(css)": "css/$1.$2",
      "(.*)\\.(js)": "js/$1.$2",
      "(.*)\\.(woff2?)": "fonts/$1.$2",
      "(.*)\\.(svg|png|gif|jpg)": "img/$1.$2"
    }
  },

How to remove hash

Hi there, I just have a question on how I can remove the hash entirely, I added the .parcelrc file and also added the below code in the package.json

"parcel-namer-rewrite": { "hashing": "never" },

Should this prevent the has being added or is there another step required, thank you

Allow removing file name hashes

The plugin works great when I 'parcel build' but when I use 'parcel watch' it adds/preserves hashes in all my icon names and I really just want the names to remain consistent. I was able to resolve this using the 'parcel-namer-custom' plugin which explicitly builds the names like "fonts/[name].[type]" and doesn't add hashes but I'd feel safer if I could use this plugin but remove hashes. I've tried setting developmentHashing and useParcelHash to false in my package.json parcel-namer-rewrite section but to no avail.

Thanks!

"parcel-namer-rewrite": {
  "developmentHashing": false,
  "useParcelHash ": false,
  "rules": {
	"(.*)\\.(css)": "css/$1.$2",
	"(.*)\\.(js)": "js/$1.$2",
	"(.*)\\.(eot|woff2?|svg|ttf)": "fonts/$1.$2",
	"(.*)\\.(png|gif|jpg)": "images/$1.$2"
  },
  "silent": false
},

multiple entry build error

Here is the part of settings in my package.json;

{
    "scripts": {
        "dev": "parcel src/**/*.html --open",
        "build": "parcel build --no-source-maps --no-content-hash",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "targets": {
        "default": {
            "source": [
                "src/index.html",
                "src/404.html"
            ]
        }
    }
}

There was an error when I executed yarn build๏ผš

parcel-namer-rewrite: ENOENT: no such file or directory, open 'C:\Users\viggo\package.json'

Obviously, in this case, the plug-in does not load the project package.json

PARCEL-NAMER-REWRITE-PROFILE leads to error

Hey there,

using

PARCEL-NAMER-REWRITE-PROFILE=development parcel build src/app.ts --no-source-maps --config .parcelrc.dev

throws the following error:

scripts/build.dev.sh: line 5: PARCEL-NAMER-REWRITE-PROFILE=development: command not found

it seems like it should be underscores, but i might just be on the wrong path completely. any help appreciated.

my package.json:

{
	...
	"packageManager": "[email protected]",
	"staticFiles": {
		"staticPath": "./src/assets",
		"staticOutPath": "./assets"
	},
	"parcel-namer-rewrite": {
		"profiles": {
			"development": {
				"rules": {
					"app.js": "tap-tap-ploom.min.dev.js"
				}
			},
			"production": {
				"rules": {
					"app.js": "tap-tap-ploom.min.js"
				}
			}
		}
	}
}

Rules: Allow referencing source directories as "from" part

So, it took me a while to get the plugin running because it seemingly didn't pick up the rules, until I carefully read the line "Rewrites all .css bundles in "styles" folder of distDir directly to distDir and adds hashes to names." again.

It may be a good thing to point it out more clearly, that rewriting relates to the distDir and not the source directories.
Besides that: Is it possible to support both, source dirs and distDirs, e.g. with a rulesSource statement?
My reasoning here is that when the files end up in dist/ they already lost some information more or less unrecoverably, if you're not willing to add a single rule for almost every file you had.

In my case, I'd like to separate the HTML files from the other assets and I have them in folders like /src/js/... and /src/css/..., but that is stripped away. That's easily doable by the file extensions, but there may be cases where you'd have multiple source folders and just don't want parcel to slam them all together. Using this plugin it would be possible to define the naming rules entirely then.

Allow relative paths

  "parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "rules": {
      "(.*).css": "css/$1.{hash}.css",
    }
  }

=>

<link rel=stylesheet href=/css/index.a0beb2ed.css>
                          ^

I am not sure if this is a bug or not.

If this is not a bug, I would like an option for relative paths:

  "parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "useRelativePaths": true,
    "rules": {
      "(.*).css": "css/$1.{hash}.css",
    }

or

  "parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "rules": {
      "(.*).css": {
        "to": "css/$1.{hash}.css",
        "useRelativePaths": true
      }
    }

=>

<link rel=stylesheet href=css/index.a0beb2ed.css>
                          ^

or relative paths is the default:

  "parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "rules": {
      "(.*).css": "css/$1.{hash}.css",
    }

=>

<link rel=stylesheet href=css/index.a0beb2ed.css>
                          ^
  "parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "rules": {
      "(.*).css": "/css/$1.{hash}.css",
    }

=>

<link rel=stylesheet href=/css/index.a0beb2ed.css>
                          ^

Following setup instructions in docs, Parcel cannot find 'default' namer

I have setup 'parcel-namer-rewrite' exactly as described in the docs here:

  1. Brand new project, nothing installed, except the latest version of Parcel, and 'parcel-namer-rewrite'.
  2. Add .parcelrc with the exact contents from the instructions here
  3. Add parcel-namer-rewrite key to my package.json, with the following contents:
"parcel-namer-rewrite": {
    "chain": "@parcel/namer-default",
    "rules": {
      "(.*).css": "assets/css/$1{.hash}.css",
      "(.*).js": "assets/js/$1{.hash}.js",
      "(.*).(jpg|png|gif|svg|webp|avif)": "assets/img/$1{.hash}.$2"
    }
  }
  1. Try to do a build to a custom directory, /build, with parcel build --dist-dir build. The build fails, with the following error:
> parcel build --dist-dir build

๐Ÿšจ Build failed.

parcel-namer-rewrite: Package 'undefined' has been found, but it's not a namer. 
Set package.json#parcel-namer-rewrite:chain to set a delegate namer ("@parcel/namer-default" by default)

I have tried, without any luck:

a. removing the chain key from package.json
b. adding "..." to the end of the list of namers: in .parcelrc, as recommended in the docs

No luck. Still fails with the same message, every time. ๐Ÿคท

[Suggestion] Join forces with 'structurize' and 'custom-dist-structure'

It may be worthwhile getting in touch with a couple of other developers that are trying to develop Parcel plugins to solve the same problem as 'parcel-namer-rewrite'. Perhaps you could all join forces and put together a single 'custom-dist-dir' plugin - which might make the job of maintaining and upgrading the plugin easier for you all.

There are a couple of projects I know of which are similar to 'parcel-namer-rewrite', and which seem to be actively maintained:

Ability to disable the plugin in development mode

I'm having trouble with this config while serving a html file.

"parcel-namer-rewrite": {
    "rules": {
      "(.*)\\.(js)": "js/$1.{hash}.$2",
      "(.*)\\.(html)": "../../backend/src/templates/$1.$2"
    },
    "silent": true
},

After some time, the dev server returns 403 and it can only be fixed by removing the html rule. I'm guessing that the dev server somehow loses access to the file after a rewrite?

I personally don't need the rewriting while in development mode, as I only want the assets to be transferred in production mode, because I need them with the hashed filenames for my backend project.

So it would be good to have a flag to disable the plugin in development mode.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.