Initial commit

This commit is contained in:
Developer
2025-04-21 16:03:20 +02:00
commit 2832896157
22874 changed files with 3092801 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,227 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>webpack Dev Middleware</h1>
</div>
It's a simple wrapper middleware for webpack. It serves the files emitted from webpack over a connect server. This should be used for **development only**.
It has a few advantages over bundling it as files:
* No files are written to disk, it handle the files in memory
* If files changed in watch mode, the middleware no longer serves the old bundle, but delays requests until the compiling has finished. You don't have to wait before refreshing the page after a file modification.
* I may add some specific optimization in future releases.
<h2 align="center">Install</h2>
```
npm install webpack-dev-middleware --save-dev
```
<h2 align="center">Usage</h2>
``` javascript
var webpackMiddleware = require("webpack-dev-middleware");
app.use(webpackMiddleware(...));
```
Example usage:
``` javascript
app.use(webpackMiddleware(webpack({
// webpack options
// webpackMiddleware takes a Compiler object as first parameter
// which is returned by webpack(...) without callback.
entry: "...",
output: {
path: "/"
// no real path is required, just pass "/"
// but it will work with other paths too.
}
}), {
// publicPath is required, whereas all other options are optional
noInfo: false,
// display no info to console (only warnings and errors)
quiet: false,
// display nothing to the console
lazy: true,
// switch into lazy mode
// that means no watching, but recompilation on every request
watchOptions: {
aggregateTimeout: 300,
poll: true
},
// watch options (only lazy: false)
publicPath: "/assets/",
// public path to bind the middleware to
// use the same as in webpack
index: "index.html",
// The index path for web server, defaults to "index.html".
// If falsy (but not undefined), the server will not respond to requests to the root URL.
headers: { "X-Custom-Header": "yes" },
// custom headers
mimeTypes: { "text/html": [ "phtml" ] },
// Add custom mime/extension mappings
// https://github.com/broofa/node-mime#mimedefine
// https://github.com/webpack/webpack-dev-middleware/pull/150
stats: {
colors: true
},
// options for formating the statistics
reporter: null,
// Provide a custom reporter to change the way how logs are shown.
serverSideRender: false,
// Turn off the server-side rendering mode. See Server-Side Rendering part for more info.
}));
```
## Advanced API
This part shows how you might interact with the middleware during runtime:
* `close(callback)` - stop watching for file changes
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
// After 10 seconds stop watching for file changes:
setTimeout(function(){
webpackDevMiddlewareInstance.close();
}, 10000);
```
* `invalidate()` - recompile the bundle - e.g. after you changed the configuration
```js
var compiler = webpack(/* see example usage */);
var webpackDevMiddlewareInstance = webpackMiddleware(compiler);
app.use(webpackDevMiddlewareInstance);
setTimeout(function(){
// After a short delay the configuration is changed
// in this example we will just add a banner plugin:
compiler.apply(new webpack.BannerPlugin('A new banner'));
// Recompile the bundle with the banner plugin:
webpackDevMiddlewareInstance.invalidate();
}, 1000);
```
* `waitUntilValid(callback)` - executes the `callback` if the bundle is valid or after it is valid again:
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
webpackDevMiddlewareInstance.waitUntilValid(function(){
console.log('Package is in a valid state');
});
```
## Server-Side Rendering
**Note: this feature is experimental and may be removed or changed completely in the future.**
In order to develop a server-side rendering application, we need access to the [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is generated with the latest build.
In the server-side rendering mode, __webpack-dev-middleware__ sets the `stat` to `res.locals.webpackStats` before invoking the next middleware, allowing a developer to render the page body and manage the response to clients.
Notice that requests for bundle files would still be responded by __webpack-dev-middleware__ and all requests will be pending until the building process is finished in the server-side rendering mode.
```javascript
// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
function normalizeAssets(assets) {
return Array.isArray(assets) ? assets : [assets]
}
app.use(webpackMiddleware(compiler, { serverSideRender: true })
// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName
// then use `assetsByChunkName` for server-sider rendering
// For example, if you have only one main chunk:
res.send(`
<html>
<head>
<title>My App</title>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.css'))
.map(path => `<link rel="stylesheet" href="${path}" />`)
.join('\n')
}
</head>
<body>
<div id="root"></div>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.js'))
.map(path => `<script src="${path}"></script>`)
.join('\n')
}
</body>
</html>
`)
})
```
<h2 align="center">Contributing</h2>
Don't hesitate to create a pull request. Every contribution is appreciated. In development you can start the tests by calling `npm test`.
<h2 align="center">Maintainers</h2>
<table>
<tbody>
<tr>
<td align="center">
<img width="150 height="150"
src="https://avatars.githubusercontent.com/SpaceK33z?v=3">
<br />
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<tr>
<tbody>
</table>
<h2 align="center">LICENSE</h2>
#### [MIT](./LICENSE)
[npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg
[npm-url]: https://npmjs.com/package/webpack-dev-middleware
[node]: https://img.shields.io/node/v/webpack-dev-middleware.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack/webpack-dev-middleware.svg
[deps-url]: https://david-dm.org/webpack/webpack-dev-middleware
[tests]: http://img.shields.io/travis/webpack/webpack-dev-middleware.svg
[tests-url]: https://travis-ci.org/webpack/webpack-dev-middleware
[cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware
[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack

View File

@@ -0,0 +1,63 @@
var pathJoin = require("./PathJoin");
var querystring = require("querystring");
var urlParse = require("url").parse;
function getFilenameFromUrl(publicPath, outputPath, url) {
var filename;
// localPrefix is the folder our bundle should be in
var localPrefix = urlParse(publicPath || "/", false, true);
var urlObject = urlParse(url);
// publicPath has the hostname that is not the same as request url's, should fail
if(localPrefix.hostname !== null && urlObject.hostname !== null &&
localPrefix.hostname !== urlObject.hostname) {
return false;
}
// publicPath is not in url, so it should fail
if(publicPath && localPrefix.hostname === urlObject.hostname && url.indexOf(publicPath) !== 0) {
return false;
}
// strip localPrefix from the start of url
if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
filename = urlObject.pathname.substr(localPrefix.pathname.length);
}
if(!urlObject.hostname && localPrefix.hostname &&
url.indexOf(localPrefix.path) !== 0) {
return false;
}
// and if not match, use outputPath as filename
return querystring.unescape(filename ? pathJoin(outputPath, filename) : outputPath);
}
// support for multi-compiler configuration
// see: https://github.com/webpack/webpack-dev-server/issues/641
function getPaths(publicPath, compiler, url) {
var compilers = compiler && compiler.compilers;
if(Array.isArray(compilers)) {
var compilerPublicPath;
for(var i = 0; i < compilers.length; i++) {
compilerPublicPath = compilers[i].options
&& compilers[i].options.output
&& compilers[i].options.output.publicPath;
if(url.indexOf(compilerPublicPath) === 0) {
return {
publicPath: compilerPublicPath,
outputPath: compilers[i].outputPath
};
}
}
}
return {
publicPath: publicPath,
outputPath: compiler.outputPath
};
}
module.exports = function(publicPath, compiler, url) {
var paths = getPaths(publicPath, compiler, url);
return getFilenameFromUrl(paths.publicPath, paths.outputPath, url);
};

View File

@@ -0,0 +1,5 @@
function pathJoin(a, b) {
return a == "/" ? "/" + b : (a || "") + "/" + b;
}
module.exports = pathJoin;

View File

@@ -0,0 +1,240 @@
var mime = require("mime");
var parseRange = require("range-parser");
var pathIsAbsolute = require("path-is-absolute");
var MemoryFileSystem = require("memory-fs");
var timestamp = require("time-stamp");
var HASH_REGEXP = /[0-9a-f]{10,}/;
module.exports = function Shared(context) {
var share = {
setOptions: function(options) {
if(!options) options = {};
if(typeof options.reportTime === "undefined") options.reportTime = false;
if(typeof options.watchOptions === "undefined") options.watchOptions = {};
if(typeof options.reporter !== "function") options.reporter = share.defaultReporter;
if(typeof options.log !== "function") options.log = console.log.bind(console);
if(typeof options.warn !== "function") options.warn = console.warn.bind(console);
if(typeof options.error !== "function") options.error = console.error.bind(console);
if(typeof options.watchDelay !== "undefined") {
// TODO remove this in next major version
options.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
options.watchOptions.aggregateTimeout = options.watchDelay;
}
if(typeof options.watchOptions.aggregateTimeout === "undefined") options.watchOptions.aggregateTimeout = 200;
if(typeof options.stats === "undefined") options.stats = {};
if(!options.stats.context) options.stats.context = process.cwd();
if(options.lazy) {
if(typeof options.filename === "string") {
var str = options.filename
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
.replace(/\\\[[a-z]+\\\]/ig, ".+");
options.filename = new RegExp("^[\/]{0,1}" + str + "$");
}
}
// defining custom MIME type
if(options.mimeTypes) mime.define(options.mimeTypes);
context.options = options;
},
defaultReporter: function(reporterOptions) {
var time = "";
var state = reporterOptions.state;
var stats = reporterOptions.stats;
var options = reporterOptions.options;
if(!!options.reportTime) {
time = "[" + timestamp("HH:mm:ss") + "] ";
}
if(state) {
var displayStats = (!options.quiet && options.stats !== false);
if(displayStats && !(stats.hasErrors() || stats.hasWarnings()) &&
options.noInfo)
displayStats = false;
if(displayStats) {
if(stats.hasErrors()) {
options.error(stats.toString(options.stats));
} else if(stats.hasWarnings()) {
options.warn(stats.toString(options.stats));
} else {
options.log(stats.toString(options.stats));
}
}
if(!options.noInfo && !options.quiet) {
var msg = "Compiled successfully.";
if(stats.hasErrors()) {
msg = "Failed to compile.";
} else if(stats.hasWarnings()) {
msg = "Compiled with warnings.";
}
options.log(time + "webpack: " + msg);
}
} else {
options.log(time + "webpack: Compiling...");
}
},
handleRangeHeaders: function handleRangeHeaders(content, req, res) {
//assumes express API. For other servers, need to add logic to access alternative header APIs
res.setHeader("Accept-Ranges", "bytes");
if(req.headers.range) {
var ranges = parseRange(content.length, req.headers.range);
// unsatisfiable
if(-1 == ranges) {
res.setHeader("Content-Range", "bytes */" + content.length);
res.statusCode = 416;
}
// valid (syntactically invalid/multiple ranges are treated as a regular response)
if(-2 != ranges && ranges.length === 1) {
// Content-Range
res.statusCode = 206;
var length = content.length;
res.setHeader(
"Content-Range",
"bytes " + ranges[0].start + "-" + ranges[0].end + "/" + length
);
content = content.slice(ranges[0].start, ranges[0].end + 1);
}
}
return content;
},
setFs: function(compiler) {
if(typeof compiler.outputPath === "string" && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
throw new Error("`output.path` needs to be an absolute path or `/`.");
}
// store our files in memory
var fs;
var isMemoryFs = !compiler.compilers && compiler.outputFileSystem instanceof MemoryFileSystem;
if(isMemoryFs) {
fs = compiler.outputFileSystem;
} else {
fs = compiler.outputFileSystem = new MemoryFileSystem();
}
context.fs = fs;
},
compilerDone: function(stats) {
// We are now on valid state
context.state = true;
context.webpackStats = stats;
// Do the stuff in nextTick, because bundle may be invalidated
// if a change happened while compiling
process.nextTick(function() {
// check if still in valid state
if(!context.state) return;
// print webpack output
context.options.reporter({
state: true,
stats: stats,
options: context.options
});
// execute callback that are delayed
var cbs = context.callbacks;
context.callbacks = [];
cbs.forEach(function continueBecauseBundleAvailable(cb) {
cb(stats);
});
});
// In lazy mode, we may issue another rebuild
if(context.forceRebuild) {
context.forceRebuild = false;
share.rebuild();
}
},
compilerInvalid: function() {
if(context.state && (!context.options.noInfo && !context.options.quiet))
context.options.reporter({
state: false,
options: context.options
});
// We are now in invalid state
context.state = false;
//resolve async
if(arguments.length === 2 && typeof arguments[1] === "function") {
var callback = arguments[1];
callback();
}
},
ready: function ready(fn, req) {
var options = context.options;
if(context.state) return fn(context.webpackStats);
if(!options.noInfo && !options.quiet)
options.log("webpack: wait until bundle finished: " + (req.url || fn.name));
context.callbacks.push(fn);
},
startWatch: function() {
var options = context.options;
var compiler = context.compiler;
// start watching
if(!options.lazy) {
var watching = compiler.watch(options.watchOptions, share.handleCompilerCallback);
context.watching = watching;
} else {
context.state = true;
}
},
rebuild: function rebuild() {
if(context.state) {
context.state = false;
context.compiler.run(share.handleCompilerCallback);
} else {
context.forceRebuild = true;
}
},
handleCompilerCallback: function(err) {
if(err) {
context.options.error(err.stack || err);
if(err.details) context.options.error(err.details);
}
},
handleRequest: function(filename, processRequest, req) {
// in lazy mode, rebuild on bundle request
if(context.options.lazy && (!context.options.filename || context.options.filename.test(filename)))
share.rebuild();
if(HASH_REGEXP.test(filename)) {
try {
if(context.fs.statSync(filename).isFile()) {
processRequest();
return;
}
} catch(e) {
}
}
share.ready(processRequest, req);
},
waitUntilValid: function(callback) {
callback = callback || function() {};
share.ready(callback, {});
},
invalidate: function(callback) {
callback = callback || function() {};
if(context.watching) {
share.ready(callback, {});
context.watching.invalidate();
} else {
callback();
}
},
close: function(callback) {
callback = callback || function() {};
if(context.watching) context.watching.close(callback);
else callback();
}
};
share.setOptions(context.options);
share.setFs(context.compiler);
context.compiler.plugin("done", share.compilerDone);
context.compiler.plugin("invalid", share.compilerInvalid);
context.compiler.plugin("watch-run", share.compilerInvalid);
context.compiler.plugin("run", share.compilerInvalid);
share.startWatch();
return share;
};

View File

@@ -0,0 +1,99 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var mime = require("mime");
var getFilenameFromUrl = require("./lib/GetFilenameFromUrl");
var Shared = require("./lib/Shared");
var pathJoin = require("./lib/PathJoin");
// constructor for the middleware
module.exports = function(compiler, options) {
var context = {
state: false,
webpackStats: undefined,
callbacks: [],
options: options,
compiler: compiler,
watching: undefined,
forceRebuild: false
};
var shared = Shared(context);
// The middleware function
function webpackDevMiddleware(req, res, next) {
function goNext() {
if(!context.options.serverSideRender) return next();
return new Promise(function(resolve) {
shared.ready(function() {
res.locals.webpackStats = context.webpackStats;
resolve(next());
}, req);
});
}
if(req.method !== "GET") {
return goNext();
}
var filename = getFilenameFromUrl(context.options.publicPath, context.compiler, req.url);
if(filename === false) return goNext();
return new Promise(function(resolve) {
shared.handleRequest(filename, processRequest, req);
function processRequest() {
try {
var stat = context.fs.statSync(filename);
if(!stat.isFile()) {
if(stat.isDirectory()) {
var index = context.options.index;
if(index === undefined || index === true) {
index = "index.html";
} else if(!index) {
throw "next";
}
filename = pathJoin(filename, index);
stat = context.fs.statSync(filename);
if(!stat.isFile()) throw "next";
} else {
throw "next";
}
}
} catch(e) {
return resolve(goNext());
}
// server content
var content = context.fs.readFileSync(filename);
content = shared.handleRangeHeaders(content, req, res);
var contentType = mime.lookup(filename);
// do not add charset to WebAssembly files, otherwise compileStreaming will fail in the client
if(!/\.wasm$/.test(filename)) {
contentType += "; charset=UTF-8";
}
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", content.length);
if(context.options.headers) {
for(var name in context.options.headers) {
res.setHeader(name, context.options.headers[name]);
}
}
// Express automatically sets the statusCode to 200, but not all servers do (Koa).
res.statusCode = res.statusCode || 200;
if(res.send) res.send(content);
else res.end(content);
resolve();
}
});
}
webpackDevMiddleware.getFilenameFromUrl = getFilenameFromUrl.bind(this, context.options.publicPath, context.compiler);
webpackDevMiddleware.waitUntilValid = shared.waitUntilValid;
webpackDevMiddleware.invalidate = shared.invalidate;
webpackDevMiddleware.close = shared.close;
webpackDevMiddleware.fileSystem = context.fs;
return webpackDevMiddleware;
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,214 @@
# time-stamp [![NPM version](https://img.shields.io/npm/v/time-stamp.svg?style=flat)](https://www.npmjs.com/package/time-stamp) [![NPM monthly downloads](https://img.shields.io/npm/dm/time-stamp.svg?style=flat)](https://npmjs.org/package/time-stamp) [![NPM total downloads](https://img.shields.io/npm/dt/time-stamp.svg?style=flat)](https://npmjs.org/package/time-stamp) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/time-stamp.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/time-stamp)
> Get a formatted timestamp.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
- [Install](#install)
- [Usage](#usage)
- [Customizing the timestamp](#customizing-the-timestamp)
- [Release history](#release-history)
* [v2.0.0](#v200)
- [About](#about)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save time-stamp
```
## Usage
```js
const timestamp = require('time-stamp');
console.log(timestamp());
//=> 2018-10-26
console.log(timestamp.utc());
//=> 2018-10-26
```
## Customizing the timestamp
You may also pass a string to format the generated timestamp.
```js
console.log(timestamp('YYYYMMDD'));
//=> 20181026
console.log(timestamp.utc('YYYYMMDD'));
//=> 20181026
```
**Supported patterns**
* `YYYY`: full year (ex: **2018**)
* `MM`: month (ex: **04**)
* `DD`: day (ex: **01**)
* `HH`: hours (ex: **12**)
* `mm`: minutes (ex: **59**)
* `ss`: seconds (ex: **09**)
* `ms`: milliseconds (ex: **532**)
**Usage Examples**
```js
console.log(timestamp('YYYYMMDD'));
//=> 20181026
console.log(timestamp.utc('YYYYMMDD'));
//=> 20181026
console.log(timestamp('YYYYMMDD:ss'));
//=> 20181026:24
console.log(timestamp.utc('YYYYMMDD:ss'));
//=> 20181026:24
console.log(timestamp('YYYY/MM/DD:mm:ss'));
//=> 2018/10/26:46:24
console.log(timestamp.utc('YYYY/MM/DD:mm:ss'));
//=> 2018/10/26:46:24
console.log(timestamp('YYYY:MM:DD'));
//=> 2018:10:26
console.log(timestamp.utc('YYYY:MM:DD'));
//=> 2018:10:26
console.log(timestamp('[YYYY:MM:DD]'));
//=> [2018:10:26]
console.log(timestamp.utc('[YYYY:MM:DD]'));
//=> [2018:10:26]
console.log(timestamp('YYYY/MM/DD'));
//=> 2018/10/26
console.log(timestamp.utc('YYYY/MM/DD'));
//=> 2018/10/26
console.log(timestamp('YYYY:MM'));
//=> 2018:10
console.log(timestamp.utc('YYYY:MM'));
//=> 2018:10
console.log(timestamp('YYYY'));
//=> 2018
console.log(timestamp.utc('YYYY'));
//=> 2018
console.log(timestamp('MM'));
//=> 10
console.log(timestamp.utc('MM'));
//=> 10
console.log(timestamp('DD'));
//=> 26
console.log(timestamp.utc('DD'));
//=> 26
console.log(timestamp('HH'));
//=> 00
console.log(timestamp.utc('HH'));
//=> 04
console.log(timestamp('mm'));
//=> 46
console.log(timestamp.utc('mm'));
//=> 46
console.log(timestamp('ss'));
//=> 24
console.log(timestamp.utc('ss'));
//=> 24
console.log(timestamp('ms'));
//=> 186
console.log(timestamp.utc('ms'));
//=> 186
```
## Release history
### v2.0.0
**Breaking changes**
Default pattern was changed from `YYYY:MM:DD` to `YYYY-MM-DD`. See [issues/3](../../issues) for more details.
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [days](https://www.npmjs.com/package/days): Days of the week. | [homepage](https://github.com/jonschlinkert/days "Days of the week.")
* [iso-week](https://www.npmjs.com/package/iso-week): Get the ISO week of the year. | [homepage](https://github.com/jonschlinkert/iso-week "Get the ISO week of the year.")
* [month](https://www.npmjs.com/package/month): Get the name or number of the current month or any month of the year. | [homepage](https://github.com/datetime/month "Get the name or number of the current month or any month of the year.")
* [months](https://www.npmjs.com/package/months): Months of the year. | [homepage](https://github.com/datetime/months "Months of the year.")
* [o-clock](https://www.npmjs.com/package/o-clock): Simple javascript utility for displaying the time in 12-hour clock format. | [homepage](https://github.com/jonschlinkert/o-clock "Simple javascript utility for displaying the time in 12-hour clock format.")
* [seconds](https://www.npmjs.com/package/seconds): Get the number of seconds for a minute, hour, day and week. | [homepage](https://github.com/jonschlinkert/seconds "Get the number of seconds for a minute, hour, day and week.")
* [week](https://www.npmjs.com/package/week): Get the current week number. | [homepage](https://github.com/datetime/week "Get the current week number.")
* [weekday](https://www.npmjs.com/package/weekday): Get the name and number of the current weekday. Or get the name of the… [more](https://github.com/datetime/weekday) | [homepage](https://github.com/datetime/weekday "Get the name and number of the current weekday. Or get the name of the weekday for a given number.")
* [year](https://www.npmjs.com/package/year): Simple utility to get the current year with 2 or 4 digits. | [homepage](https://github.com/jonschlinkert/year "Simple utility to get the current year with 2 or 4 digits.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 31 | [jonschlinkert](https://github.com/jonschlinkert) |
| 7 | [doowb](https://github.com/doowb) |
| 1 | [evocateur](https://github.com/evocateur) |
| 1 | [mendenhallmagic](https://github.com/mendenhallmagic) |
| 1 | [mvanroon](https://github.com/mvanroon) |
| 1 | [leesei](https://github.com/leesei) |
| 1 | [sleagon](https://github.com/sleagon) |
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on October 26, 2018._

View File

@@ -0,0 +1,5 @@
declare function timestamp(pattern?: string | Date, date?: Date): string
declare function timestampUTC(pattern?: string | Date, date?: Date): string
export default timestamp
export { timestampUTC as utc };

View File

@@ -0,0 +1,43 @@
/*!
* time-stamp <https://github.com/jonschlinkert/time-stamp>
*
* Copyright (c) 2015-2018, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var dateRegex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/g;
var timespan = {
YYYY: ['getFullYear', 4],
YY: ['getFullYear', 2],
MM: ['getMonth', 2, 1], // getMonth is zero-based, thus the extra increment field
DD: ['getDate', 2],
HH: ['getHours', 2],
mm: ['getMinutes', 2],
ss: ['getSeconds', 2],
ms: ['getMilliseconds', 3]
};
var timestamp = function(str, date, utc) {
if (typeof str !== 'string') {
date = str;
str = 'YYYY-MM-DD';
}
if (!date) date = new Date();
return str.replace(dateRegex, function(match, key, rest) {
var args = timespan[key];
var name = args[0];
var chars = args[1];
if (utc === true) name = 'getUTC' + name.slice(3);
var val = '00' + String(date[name]() + (args[2] || 0));
return val.slice(-chars) + (rest || '');
});
};
timestamp.utc = function(str, date) {
return timestamp(str, date, true);
};
module.exports = timestamp;

View File

@@ -0,0 +1,120 @@
{
"_from": "time-stamp@^2.0.0",
"_id": "time-stamp@2.2.0",
"_inBundle": false,
"_integrity": "sha512-zxke8goJQpBeEgD82CXABeMh0LSJcj7CXEd0OHOg45HgcofF7pxNwZm9+RknpxpDhwN4gFpySkApKfFYfRQnUA==",
"_location": "/webpack-dev-middleware/time-stamp",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "time-stamp@^2.0.0",
"name": "time-stamp",
"escapedName": "time-stamp",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/webpack-dev-middleware"
],
"_resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-2.2.0.tgz",
"_shasum": "917e0a66905688790ec7bbbde04046259af83f57",
"_spec": "time-stamp@^2.0.0",
"_where": "D:\\developments\\teaser-inertia\\nova-components\\NovaLeader\\node_modules\\webpack-dev-middleware",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/time-stamp/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Daniel Stockman",
"url": "http://evocateur.org"
},
{
"name": "Drew",
"url": "https://github.com/mendenhallmagic"
},
{
"name": "Jon Schlinkert",
"url": "http://twitter.com/jonschlinkert"
},
{
"name": "leesei",
"url": "https://leesei.github.io"
}
],
"deprecated": false,
"description": "Get a formatted timestamp.",
"devDependencies": {
"gulp-format-md": "^1.0.0",
"mocha": "^5.2.0",
"pad-left": "^2.1.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/jonschlinkert/time-stamp",
"keywords": [
"console",
"date",
"format",
"formatting",
"log",
"pretty",
"stamp",
"terminal",
"time",
"time-stamp"
],
"license": "MIT",
"main": "index.js",
"name": "time-stamp",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/time-stamp.git"
},
"scripts": {
"test": "mocha"
},
"types": "index.d.ts",
"verb": {
"run": true,
"toc": true,
"layout": "default",
"tasks": [
"readme"
],
"helpers": [
"./helpers.js"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"days",
"iso-week",
"month",
"months",
"o-clock",
"seconds",
"week",
"weekday",
"year"
]
},
"lint": {
"reflinks": true
}
},
"version": "2.2.0"
}

View File

@@ -0,0 +1,81 @@
{
"_from": "webpack-dev-middleware@1.12.2",
"_id": "webpack-dev-middleware@1.12.2",
"_inBundle": false,
"_integrity": "sha512-FCrqPy1yy/sN6U/SaEZcHKRXGlqU0DUaEBL45jkUYoB8foVb6wCnbIJ1HKIx+qUFTW+3JpVcCJCxZ8VATL4e+A==",
"_location": "/webpack-dev-middleware",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "webpack-dev-middleware@1.12.2",
"name": "webpack-dev-middleware",
"escapedName": "webpack-dev-middleware",
"rawSpec": "1.12.2",
"saveSpec": null,
"fetchSpec": "1.12.2"
},
"_requiredBy": [
"/webpack-dev-server"
],
"_resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz",
"_shasum": "f8fc1120ce3b4fc5680ceecb43d777966b21105e",
"_spec": "webpack-dev-middleware@1.12.2",
"_where": "D:\\developments\\teaser-inertia\\nova-components\\NovaLeader\\node_modules\\webpack-dev-server",
"author": {
"name": "Tobias Koppers @sokra"
},
"bugs": {
"url": "https://github.com/webpack/webpack-dev-middleware/issues"
},
"bundleDependencies": false,
"dependencies": {
"memory-fs": "~0.4.1",
"mime": "^1.5.0",
"path-is-absolute": "^1.0.0",
"range-parser": "^1.0.3",
"time-stamp": "^2.0.0"
},
"deprecated": false,
"description": "Offers a dev middleware for webpack, which arguments a live bundle to a directory",
"devDependencies": {
"codecov.io": "^0.1.6",
"eslint": "^4.0.0",
"express": "^4.14.0",
"file-loader": "^0.11.2",
"istanbul": "^0.4.5",
"mocha": "^3.0.2",
"mocha-sinon": "^2.0.0",
"should": "^11.1.0",
"sinon": "^2.3.8",
"supertest": "^3.0.0",
"webpack": "^3.0.0"
},
"engines": {
"node": ">=0.6"
},
"files": [
"middleware.js",
"lib/"
],
"homepage": "http://github.com/webpack/webpack-dev-middleware",
"license": "MIT",
"main": "middleware.js",
"name": "webpack-dev-middleware",
"peerDependencies": {
"webpack": "^1.0.0 || ^2.0.0 || ^3.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/webpack/webpack-dev-middleware.git"
},
"scripts": {
"beautify": "npm run lint -- --fix",
"cover": "istanbul cover node_modules/mocha/bin/_mocha",
"lint": "eslint *.js lib test",
"posttest": "npm run -s lint",
"test": "mocha --full-trace --check-leaks",
"travis": "npm run cover -- --report lcovonly && npm run lint"
},
"version": "1.12.2"
}