GithubHelp home page GithubHelp logo

keithamus / postcss-hash Goto Github PK

View Code? Open in Web Editor NEW
24.0 4.0 8.0 323 KB

PostCSS plugin to replace output file names with HASH algorithms (md5, sha256, sha512, etc) and string length of your choice - for cache busting

License: MIT License

JavaScript 100.00%

postcss-hash's Introduction

PostCSS Hash Build Status

PostCSS plugin to replace output file names with HASH algorithms (md5, sha256, sha512, etc) and string length of your choice - for cache busting.

# input
postcss input.css -o output.css

# output
output.a1b2c3d4e5.css

# ./manifest.json
{
  "output.css": "output.a1b2c3d4e5.css",
}
# input
postcss css/in/*.css --dir css/out/

# output
file1.a516675ef8.css
file2.aa36634cc4.css
file3.653f682ad9.css
file4.248a1e8f9e.css
file5.07534806bd.css

# ./manifest.json
{
  "file1.css": "file1.a516675ef8.css",
  "file2.css": "file2.aa36634cc4.css",
  "file3.css": "file3.653f682ad9.css",
  "file4.css": "file4.248a1e8f9e.css",
  "file5.css": "file5.07534806bd.css"
}

Usage

// postcss.config.js
module.exports = (ctx) => ({
    plugins: {
        'postcss-hash': {
            algorithm: 'sha256',
            trim: 20,
            manifest: './manifest.json'
        },
    }
});

Options

algorithm (string, default: 'md5')

Uses node's inbuilt crypto module. Pass any digest algorithm that is supported in your environment. Possible values are: md5, md4, md2, sha, sha1, sha224, sha256, sha384, sha512.

includeMap (boolean, default: false)

Setting includeMap to true will allow postcss-hash to hash the name of the sourcemap, as well hash the CSS including the sourceMappingURL comment. You can set this option to true if you care about the hashed fingerprints matching the contents of the CSS file, and don't mind a performance hit of regenerating the CSS twice.

trim (number, default: 10)

Hash's length.

manifest (string, default: './manifest.json')

Will output a manifest file with key: value pairs.

name (function, default: ({dir, name, hash, ext}) => path.join(dir, name + '.' + hash + ext)

Pass a function to customise the name of the output file. The function is given an object of string values:

  • dir: the directory name as a string
  • name: the name of the file, excluding any extensions
  • hash: the resulting hash digest of the file
  • ext: the extension of the file

NOTE:

  1. The values will be either appended or replaced. If this file needs be recreated on each run, you'll have to manually delete it.
  2. keys are generated with files' basename. If you have ./input/A/one.css & ./input/B/one.css, only the last entry will exist.

updateEntry (function, default: (originalName, hashedName) => { "fileName.css": "hashedName.css"}

Pass a function to customize manifest entries. The function is given

  • originalName: the original file name.
  • hashedName: the compiled file name.

The function must return an object with the fileName as a key and whatever value you want. E.g.:

function e(originalName, hashedName) {
  var newData = {};
  var key = path.parse(originalName).base;
  var value = path.parse(hashedName).base;

  newData[key] = { src: value, css: true };

  return newData;
}

See PostCSS docs for examples for your environment.

Version: 0.2.0
Updated on: August 29, 2017

postcss-hash's People

Contributors

dacodekid avatar dependabot[bot] avatar keithamus avatar koddsson avatar manuelpuyol avatar tetsuharuohzeki 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  avatar

Watchers

 avatar  avatar  avatar  avatar

postcss-hash's Issues

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string

I'm having trouble with my script. I have

// postcss.config.js
const purgecss = require("@fullhuman/postcss-purgecss")({
    // Specify the paths to all of the template files in your project
    content: ["./themes/losvast20/**/*.ejs"],

    // Include any special characters you're using in this regular expression
    defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
});

const nano = require("cssnano")({
    preset: "default"
});

const hash = require("postcss-hash")({
    algorithm: "sha256",
    trim: 20,
    manifest: "./manifest.json"
});

console.log("*******", process.env.NODE_ENV);
process.env.NODE_ENV = "production";

module.exports = {
    from: undefined,
    plugins: [
        require("postcss-nested"),
        require("postcss-color-function"),
        require("tailwindcss"),
        ...(process.env.NODE_ENV === "production" ? [purgecss, nano, hash] : [])
    ]
};

It worked up to the point that I added hashing.

At that point I got an error

ERROR Asset render failed: css/style.css
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.dirname (path.js:1260:5)
    at Object.rename (/Users/code/clients/losvast/node_modules/postcss-hash/utils.js:27:19)
    at /Users/code/clients/losvast/node_modules/postcss-hash/index.js:23:32

I'm completely new to postcss and am using it in this project to become more familiar

Crashes when used with postcss-modules

Disclaimer, I'm not fully acquainted with the PostCSS architecture.

When using 'postcss-modules' alongside 'postcss-hash', the latter throws when it cannot find a result.opt.to field. I believe this to happen because the former adds a 'result' which it doesn't intend to be written to file. So to achieve that it just doesn't set a opts.to field.

The fix for 'postcss-hash' is quite simple - ignore the file. Include a line if (!result.opt.to) return; at the top of the core function.

I guess my question is; is this an intended behaviour of PostCSS plugins that just isn't handled here? Or is 'postcss-modules' misbehaving?

Example for setting custom name

Hi @keithamus.

Is it possible to provide an example for setting a custom name? and the dir option.

Now its

{
  "main.css": "main.a80bb6bc4faf8fd.css"
}

But I would like i.e

{
  "css/build/main.css": "css/build/main.a80bb6bc4faf8fd.css"
}

Thanks!

Add option to remove input file

Thanks for this plugin! ๐Ÿ‘

I guess most users would like to remove the input file when the hashed output is done.

Would it be possible?

postcss-hash use the inputted css to calc hash even if the inputted css includes and inlines other css files by `postcss-import`

postcss-hash use the inputted css to calc hash even if the inputted css includes and inlines other css files by postcss-import

Environment

  • postcss-hash: 0.2.1
  • postcss: 6.0.23
  • postcss-import: 11.1.0

Examples

There are some files:

a.css
b.css

a.css

@import './b.css';

b.css

.bar-foo {
	color: red;
}

postcss.config.js

// postcss.config.js
module.exports = (ctx) => ({
    plugins: {
    	'postcss-import': {},
        'postcss-hash': {
            algorithm: 'sha256',
            trim: 20,
            manifest: './manifest.json'
        },
    }
});

generated code

.bar-foo will be inlined by postcss-import

.bar-foo {
	color: red;
}

Steps to Reproduce

  1. With the above environment, run postcss.
  2. step 1 will generate the above generated code.

Actual Result

By the code, postcss-hash calcs based on a.css. Not based on the generated code.

This means that the hash will not change if I change b.css but I don't change a.css.

Expected Result

The hash will change if I change b.css.

feature: include full path in manifest

would like to suggest / add an option to include the full directory path of the output files in the manifest. afaik this is just a matter of passing the full path rather than the base name in the following function

function data(originalName, hashedName, opts) {
    var key = path.parse(originalName).base;
    var value = path.parse(hashedName).base;

    return opts.updateEntry(originalName, hashedName);
}

This could be toggled using a fullPath boolean option?

Also curious about the status of this repo, as it's only on v2.0.0 while the npm package is on v3.0.0.

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.