This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

View File

@@ -0,0 +1,16 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
max_line_length = 80
trim_trailing_whitespace = true
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

View File

@@ -0,0 +1,20 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JSCodeStyleSettings version="0">
<option name="IMPORT_PREFER_ABSOLUTE_PATH" value="TRUE" />
</JSCodeStyleSettings>
<ScalaCodeStyleSettings>
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
</ScalaCodeStyleSettings>
<TypeScriptCodeStyleSettings version="0">
<option name="IMPORT_PREFER_ABSOLUTE_PATH" value="TRUE" />
</TypeScriptCodeStyleSettings>
<codeStyleSettings language="JavaScript">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

View File

@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/static-site-generator-webpack-plugin.iml" filepath="$PROJECT_DIR$/.idea/static-site-generator-webpack-plugin.iml" />
</modules>
</component>
</project>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
</set>
</option>
</component>
</project>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- "14"
- "16"
after_script:
- npm run coveralls

View File

@@ -0,0 +1,7 @@
## 4.0.0
- Minimum webpack version is >= 4.0.0
- Supported nodejs version >= 8.9.0
- Update all dependencies
- Update tests
- Performance and memory improvement (Use less stats object when calling stats.toJson())

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Mark Dalgleish
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,237 @@
[![Build Status](https://img.shields.io/travis/slorber/static-site-generator-webpack-plugin/master.svg?style=flat-square)](http://app.travis-ci.com/slorber/static-site-generator-webpack-plugin) [![npm](https://img.shields.io/npm/v/@slorber/static-site-generator-webpack-plugin.svg?style=flat-square)](https://npmjs.org/package/@slorber/static-site-generator-webpack-plugin)
# FORK FOR DOCUSAURUS
This is a fork used for Docusaurus
This fixes [trailing slash issues](https://github.com/facebook/docusaurus/issues/3372) by allowing to output `/filename.html` instead of `/filename/index.html` by exposing a `preferFoldersOutput: false` option.
It is based on a previous fork by Endiliey: https://github.com/endiliey/static-site-generator-webpack-plugin
I don't know the reasons of the initial fork.
We also added a `concurrency: 32` option to avoid overloading the system with too much IO (using [p-map](https://github.com/sindresorhus/p-map))
# static site generator webpack plugin
Minimal, unopinionated static site generator powered by webpack.
Bring the world of server rendering to your static build process. Either provide an array of paths to be rendered and a matching set of `index.html` files will be rendered in your output directory by executing your own custom, webpack-compiled render function.
This plugin works particularly well with universal libraries like [React](https://github.com/facebook/react) and [React Router](https://github.com/rackt/react-router) since it allows you to pre-render your routes at build time, rather than requiring a Node server in production.
## Install
```bash
$ npm install --save-dev @slorber/static-site-generator-webpack-plugin
```
## Usage
Ensure you have webpack installed, e.g. `npm install -g webpack`
### webpack.config.js
```js
const StaticSiteGeneratorPlugin = require('@slorber/static-site-generator-webpack-plugin');
module.exports = {
entry: './index.js',
output: {
filename: 'index.js',
path: 'dist',
/* IMPORTANT!
* You must compile to UMD or CommonJS
* so it can be required in a Node context: */
libraryTarget: 'umd'
},
plugins: [
new StaticSiteGeneratorPlugin({
paths: [
'/hello/',
'/world/'
],
locals: {
// Properties here are merged into `locals`
// passed to the exported render function
greet: 'Hello'
}
})
]
};
```
### index.js
Sync rendering:
```js
module.exports = function render(locals) {
return '<html>' + locals.greet + ' from ' + locals.path + '</html>';
};
```
Async rendering via callbacks:
```js
module.exports = function render(locals, callback) {
callback(null, '<html>' + locals.greet + ' from ' + locals.path + '</html>');
};
```
Async rendering via promises:
```js
module.exports = function render(locals) {
return Promise.resolve('<html>' + locals.greet + ' from ' + locals.path + '</html>');
};
```
## Multi rendering
If you need to generate multiple files per render, or you need to alter the path, you can return an object instead of a string, where each key is the path, and the value is the file contents:
```js
module.exports = function render() {
return {
'/': '<html>Home</html>',
'/hello': '<html>Hello</html>',
'/world': '<html>World</html>'
};
};
```
Note that this will still be executed for each entry in your `paths` array in your plugin config.
## Default locals
```js
// The path currently being rendered:
locals.path;
// An object containing all assets:
locals.assets;
// Advanced: Webpack's stats object:
locals.webpackStats;
```
Any additional locals provided in your config are also available.
## Custom file names
By providing paths that end in `.html`, you can generate custom file names other than the default `index.html`. Please note that this may break compatibility with your router, if you're using one.
```js
module.exports = {
...
plugins: [
new StaticSiteGeneratorPlugin({
paths: [
'/index.html',
'/news.html',
'/about.html'
]
})
]
};
```
## Globals
If required, you can provide an object that will exist in the global scope when executing your render function. This is particularly useful if certain libraries or tooling you're using assumes a browser environment.
For example, when using Webpack's `require.ensure`, which assumes that `window` exists:
```js
module.exports = {
...,
plugins: [
new StaticSiteGeneratorPlugin({
globals: {
window: {}
}
})
]
}
```
## Asset support
template.ejs
```ejs
<% css.forEach(function(file){ %>
<link href="<%- file %>" rel="stylesheet">
<% }); %>
<% js.forEach(function(file){ %>
<script src="<%- file %>" async></script>
<% }); %>
```
index.js
```js
if (typeof global.document !== 'undefined') {
const rootEl = global.document.getElementById('outlay');
React.render(
<App />,
rootEl,
);
}
export default (data) => {
const assets = Object.keys(data.webpackStats.compilation.assets);
const css = assets.filter(value => value.match(/\.css$/));
const js = assets.filter(value => value.match(/\.js$/));
return template({ css, js, ...data});
}
```
## Specifying entry
This plugin defaults to the first chunk found. While this should work in most cases, you can specify the entry name if needed:
```js
module.exports = {
...,
plugins: [
new StaticSiteGeneratorPlugin({
entry: 'main'
})
]
}
```
## Compression support
Generated files can be compressed with [compression-webpack-plugin](https://github.com/webpack/compression-webpack-plugin), but first ensure that this plugin appears before compression-webpack-plugin in your plugins array:
```js
const StaticSiteGeneratorPlugin = require('@slorber/static-site-generator-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
...
plugins: [
new StaticSiteGeneratorPlugin(...),
new CompressionPlugin(...)
]
};
```
## Related projects
- [react-router-to-array](https://github.com/alansouzati/react-router-to-array) - useful for avoiding hardcoded lists of routes to render
- [gatsby](https://github.com/gatsbyjs/gatsby) - opinionated static site generator built on top of this plugin
## License
[MIT License](http://markdalgleish.mit-license.org)

View File

@@ -0,0 +1,183 @@
const RawSource = require('webpack-sources/lib/RawSource');
const evaluate = require('eval');
const path = require('path');
const pMap = require("p-map");
const pluginName = 'static-site-generator-webpack-plugin'
// Not easy to define a reasonable option default
// Will still be better than Infinity
// See also https://github.com/sindresorhus/p-map/issues/24
const DefaultConcurrency = 32;
class StaticSiteGeneratorWebpackPlugin {
constructor(options) {
options = options || {};
this.concurrency = options.concurrency || DefaultConcurrency;
this.entry = options.entry;
this.paths = Array.isArray(options.paths) ? options.paths : [options.paths || '/'];
this.locals = options.locals;
this.globals = options.globals;
this.preferFoldersOutput = options.preferFoldersOutput;
}
findAsset(entry, compilation, webpackStatsJson) {
if (!entry) {
const chunkNames = Object.keys(webpackStatsJson.assetsByChunkName);
entry = chunkNames[0];
}
const asset = compilation.assets[entry];
if (asset) return asset;
let chunkValue = webpackStatsJson.assetsByChunkName[entry];
if (!chunkValue) return null;
// Webpack outputs an array for each chunk when using sourcemaps
if (chunkValue instanceof Array) {
// Is the main bundle always the first element?
chunkValue = chunkValue.find((filename) => /\.js$/.test(filename));
}
return compilation.assets[chunkValue];
}
// Shamelessly stolen from html-webpack-plugin - Thanks @ampedandwired :)
getAssetsFromCompilation(compilation, webpackStatsJson) {
const assets = {};
for (const chunk in webpackStatsJson.assetsByChunkName) {
let chunkValue = webpackStatsJson.assetsByChunkName[chunk];
// Webpack outputs an array for each chunk when using sourcemaps
if (chunkValue instanceof Array) {
// Is the main bundle always the first JS element?
chunkValue = chunkValue.find((filename) => /\.js$/.test(filename));
}
if (compilation.options.output.publicPath) {
chunkValue = compilation.options.output.publicPath + chunkValue;
}
assets[chunk] = chunkValue;
}
return assets;
}
async injectApp(compilation) {
const webpackStats = compilation.getStats();
const webpackStatsJson = webpackStats.toJson({ all: false, assets: true }, true);
const asset = this.findAsset(this.entry, compilation, webpackStatsJson)
if (asset == null) {
throw new Error(`Source file not found: "${this.entry}"`);
}
const assets = this.getAssetsFromCompilation(compilation, webpackStatsJson);
const source = asset.source();
let render = evaluate(
source,
/* filename: */ this.entry,
/* scope: */ this.globals,
/* includeGlobals: */ true
);
if (render.hasOwnProperty('default')) {
render = render['default'];
}
if (typeof render !== 'function') {
throw new Error(`Export from "${this.entry}" must be a function that returns an HTML string. Is output.libraryTarget in the configuration set to "umd"?`);
}
return pMap(
this.paths,
(outputPath) => this.renderPath(outputPath, render, assets, webpackStats, compilation),
{concurrency: this.concurrency}
);
}
pathToAssetName(outputPath) {
const outputFileName = outputPath.replace(/^(\/|\\)/, ''); // Remove leading slashes for webpack-dev-server
// Paths ending with .html are left untouched
if (/\.(html?)$/i.test(outputFileName)) {
return outputFileName;
}
// Legacy retro-compatible behavior
if (typeof this.preferFoldersOutput === 'undefined') {
return path.join(outputFileName, 'index.html');
}
// New behavior: we can say if we prefer file/folder output
// Useful resource: https://github.com/slorber/trailing-slash-guide
if (outputPath === '' || outputPath.endsWith('/') || this.preferFoldersOutput) {
return path.join(outputFileName, 'index.html');
} else {
return `${outputFileName}.html`;
}
}
renderPath(outputPath, render, assets, webpackStats, compilation) {
const locals = {
path: outputPath,
assets,
webpackStats,
...this.locals,
};
const renderPromise = render.length < 2
? Promise.resolve(render(locals))
: new Promise((resolve, reject) => {
render(locals, (err, succ) => {
if (err) {
return reject(err)
}
return resolve(succ)
})
});
return renderPromise
.then((output) => {
const outputByPath = typeof output === 'object' ? output : { [outputPath]: output } ;
const assetGenerationPromises = Object.keys(outputByPath).map((key) => {
const rawSource = outputByPath[key];
const assetName = this.pathToAssetName(key);
// console.log("pathToAssetName: " + key + " => " + assetName);
if (compilation.assets[assetName]) {
return;
}
compilation.assets[assetName] = new RawSource(rawSource);
});
return Promise.all(assetGenerationPromises);
})
.catch((err) => {
compilation.errors.push(err.stack);
});
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
compilation.hooks.optimizeAssets.tapAsync(
pluginName,
(_, done) => {
this.injectApp(compilation)
.then(() => {
done()
}, (err) => {
compilation.errors.push(err.stack);
done();
})
}
);
});
}
}
module.exports = StaticSiteGeneratorWebpackPlugin;
module.exports.default = StaticSiteGeneratorWebpackPlugin;

View File

@@ -0,0 +1,3 @@
module.exports = {
coveragePathIgnorePatterns: ["/node_modules/", "/test/"]
}

View File

@@ -0,0 +1,46 @@
{
"name": "@slorber/static-site-generator-webpack-plugin",
"version": "4.0.7",
"publishConfig": {
"access": "public"
},
"description": "Minimal, unopinionated static site generator powered by webpack",
"main": "index.js",
"scripts": {
"test": "jest test",
"coverage": "jest --coverage",
"coveralls": "jest --coverage --coverageReporters=text-lcov | coveralls"
},
"repository": {
"type": "git",
"url": "https://github.com/slorber/static-site-generator-webpack-plugin"
},
"author": "Mark Dalgleish",
"license": "MIT",
"bugs": {
"url": "https://github.com/slorber/static-site-generator-webpack-plugin/issues"
},
"homepage": "https://github.com/slorber/static-site-generator-webpack-plugin",
"dependencies": {
"eval": "^0.1.8",
"p-map": "^4.0.0",
"webpack-sources": "^3.2.2"
},
"engines": {
"node": ">=14"
},
"devDependencies": {
"@babel/core": "^7.6.4",
"@babel/preset-env": "^7.6.3",
"async": "^2.0.1",
"babel-loader": "^8.0.0",
"compression-webpack-plugin": "^9.0.1",
"ejs": "^2.3.4",
"glob": "^7.0.3",
"jest": "^24.9.0",
"node-dir": "^0.1.17",
"rimraf": "^2.4.4",
"webpack": "^5.64.2",
"webpack-stats-plugin": "^1.0.3"
}
}