Giter VIP home page Giter VIP logo

html-render-webpack-plugin's Introduction

html-render-webpack-plugin

npm

Plugin to create HTML files with JavaScript.

Setup

$ npm install webpack html-render-webpack-plugin
# OR
$ yarn add webpack html-render-webpack-plugin

webpack.config.js

module.exports = {
  ...,
  plugins: [new HtmlRenderPlugin().rendererPlugin]
};

Multiple configurations

If you use multiple webpack configurations you may want to add information from other builds when rendering.

For example, you may wish to add a script tag where the name includes a hash. The asset name comes from the output of one build (browser assets) whilst the render is performed in another build (node rendering).

src/render.js

export default ({ assetsByChunkName }) => {
  return `<html>
<body>
  <script src="${assetsByChunkName.main}"></script>
</body>
</html>`;
};

dist/index.html

<html>
  <body>
    <script src="/main-daf2166db871ad045ea4.js"></script>
  </body>
</html>

See the full example below.

Multiple configuration setup

Add htmlRenderPlugin.statsCollectorPlugin to the plugins of all configurations you want to get stats for.

Add htmlRenderPlugin.rendererPlugin to the plugin of the configuration you want to use to render html.

HtmlRenderPlugin will then pass the Webpack Stats for those builds into your render function.

webpack.config.js

const { HtmlRenderPlugin } = require("html-render-webpack-plugin");

const htmlRenderPlugin = new HtmlRenderPlugin();
module.exports = [
  {
    name: "render",
    target: "node", // Creates assets that render HTML that runs well in node
    plugins: [htmlRenderPlugin.rendererPlugin],
  },
  {
    name: "client",
    target: "web", // Creates files that run on the browser
    plugins: [htmlRenderPlugin.statsCollectorPlugin],
  },
];

See examples for more details.

Options

Option: renderEntry string

default: "main"

The webpack entry to use when rendering. Override when using object syntax.

webpack.config.js

module.exports = {
  entry: {
    myRender: "./src/myRender.js",
  },
  plugins: [
    new HtmlRenderPlugin({
      renderEntry: "myRender",
    }).render,
  ],
};

Option: renderDirectory string

The location to create rendered files. Defaults to the rendered assets output.

Useful when deploying HTML files separate to other build assets.

Option: routes Array<object|string>

default: [""]

Renders a HTML page for each value in the array. A route can be a string showing the folder or file to render, or an object containing a route parameter. index.html is automatically appended for paths.

const routes = ["", "contact", "about"];

A route can be an object, containing a route parameter.

const routes = [
  {
    route: "en-us/contact",
    language: "en-us",
  },
  {
    route: "en-us/about",
    language: "en-us",
  },
  {
    route: "en-au/contact",
    language: "en-au",
  },
  {
    route: "/en-au/about",
    language: "en-au",
  },
];

Option: mapStatsToParams Function

default: ({webpackStats, ...route}) => ({ webpackStats })

mapStatsToParams should accept webpackStats and route information and returns values to be passed into render. The function is called individually for each render.

Recommendation: mapStatsToParams is an opportunity to limit what information is provided to your render function. Keeping the boundary between your build code and application code simple. Avoid passing all webpackStats into your render function, pull out only the information needed. It is recommended to override the default mapStatsToParams behaviour.

Option: transformFilePath Function

default: (route) => route.route ? route.route : route

By default a file will be created using the route value. For example the value {route: '/about/us'} would create about/us/index.html

If you want to use a different file path you can provide a transformFilePath function.

new HtmlRenderPlugin({
  ...
  transformFilePath: ({ route, language }) => `${language}/${route}`
  routes: [
    { route: '/about/us', language: 'en-us' },
    { route: '/about/us', language: 'en-au' }
  ]
});

In this example, the resulting files will be

  • en-us/about/us/index.html

  • en-au/about/us/index.html

Option: renderConcurrency string ("serial"|"parallel")

default: "serial"

By default each file will be rendered one after the other, creating a simple sequential build log. When renders with significant asynchronous work you may want to have each render run in parallel.

new HtmlRenderPlugin({
  renderConcurrency: 'parallel'
});

Option: skipAssets Function

default: false

After waiting for all builds to complete HtmlRenderPlugin will render all routes. For particularly large projects with a large number of routes this can take some time. For watch builds you may want to skip emitting assets, relying on createDevRouter instead.

Option: transformExpressPath Function

default: (route) => route.route ? route.route : route

When creating a dev router each route will be attached to the router using it's route value.

If you want to use a different express route you can provide a transformExpressPath function.

Dev Server

Create an Express Middleware to attach to Webpack Dev Server to speed up development builds.

For particularly large projects with slow renders and a large number of routes rendering every route on every build can slow down development. The dev server allows you to only render the pages as they are needed during development, whilst ensuring the resulting render works like the full production render.

Using the Webpack Dev Server Node API create a dev server and attach the dev HtmlRenderPlugin router to it. When pages are requested they will be rendered just-in-time, using the same method of rendering as production.

const htmlRenderPlugin = new HtmlRenderPlugin({
  routes,
  skipAssets: true,
});

const compiler = webpack(config);

const webpackDevServer = new WebpackDevServer(compiler, {
  before: (app) => {
    app.use(htmlRenderPlugin.createDevRouter());
  },
});

webpackDevServer.listen("8081");

Note: Ensure that you use the same htmlRenderPlugin created for your webpack configuration as you use for your dev server.

Manual just-in-time rendering

As an alternative to using the default dev server you can access renderWhenReady to apply your own just-in-time rendering.

Just call renderWhenReady with any route, and the next time the renderer is ready the render will be performed.

Note: Be careful to only use routes that are generated in a production. Not doing this can lead to differences between development and production builds.

Example: Using an Express App to render a dynamic path with ids.

app.get('/books/:id', (req, res) => {
  res.send(await htmlRenderPlugin.renderWhenReady({route: '/books/_id'}))
})

Errors returned during this render will contain a webpackStats attribute when available. This can be useful when rendering your own error pages.

Examples

Example: Client assets

An example of using mapStatsToParams to create <script> tags.

src/render.js

export default ({ mainChunk }) => {
  return `<html>
  <body>
    <script src="${mainChunk}"></script>
  </body>
  </html>`;
};

webpack.config.js

const path = require("path");

const { htmlRenderPlugin, htmlRenderClientPlugin } = createHtmlRenderPlugin({
  mapStatsToParams: ({ webpackStats }) => ({
    mainChunk: webpackStats.toJson().assetsByChunkName.main,
  }),
});

module.exports = [
  {
    name: "client",
    target: "web",
    output: {
      filename: "client-[name]-[contenthash].js",
    },
    entry: path.resolve("src", "client.js"),
    plugins: [htmlRenderPlugin.statsCollectorPlugin],
  },
  {
    name: "render",
    target: "node",
    output: {
      libraryExport: "default",
      libraryTarget: "umd2",
      filename: "render-[name]-[contenthash].js",
    },
    entry: path.resolve("src", "render.js"),
    plugins: [htmlRenderPlugin.rendererPlugin],
  },
];

Migration Guides

Migration from v1 to v2? Checkout the Migration Guide.

html-render-webpack-plugin's People

Contributors

jahredhope avatar mattcompiles avatar mrm007 avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

mrm007

html-render-webpack-plugin's Issues

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Rate Limited

These updates are currently rate limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/jest to v26.0.24
  • chore(deps): update typescript-eslint monorepo to v4.33.0 (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • chore(deps): update actions/checkout action to v3
  • chore(deps): update actions/setup-node action to v3
  • chore(deps): update dependency eslint to v8
  • chore(deps): update dependency semantic-release to v19
  • chore(deps): update dependency ts-node to v10
  • chore(deps): update jest monorepo to v28 (major) (@types/jest, jest, ts-jest)
  • chore(deps): update node.js to v16
  • chore(deps): update react monorepo to v18 (major) (react, react-dom)
  • chore(deps): update typescript-eslint monorepo to v5 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • fix(deps): update dependency chalk to v5
  • fix(deps): update dependency schema-utils to v4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/release.yml
  • actions/checkout v2
  • actions/setup-node v1
.github/workflows/test.yml
  • actions/checkout v2
  • actions/setup-node v1
npm
package.json
  • chalk ^4.1.0
  • eval ^0.1.4
  • exception-formatter ^2.1.2
  • schema-utils ^3.0.0
  • @types/debug ^4.1.5
  • @types/express ^4.17.11
  • @types/jest ^26.0.20
  • @types/webpack ^4.41.26
  • @typescript-eslint/eslint-plugin ^4.15.0
  • @typescript-eslint/parser ^4.15.0
  • commitizen 4.2.3
  • cz-conventional-changelog 3.3.0
  • eslint 7.19.0
  • express ^4.17.1
  • jest 26.6.3
  • memfs ^3.2.0
  • memoizee ^0.4.15
  • prettier 2.2.1
  • react ^17.0.1
  • react-dom ^17.0.1
  • semantic-release 17.3.8
  • ts-jest ^26.5.1
  • ts-node ^9.1.1
  • typescript ^4.1.4
  • webpack ^5.0.0
  • webpack-merge ^5.0.0
  • express >=4.0.0
nvm
.nvmrc
  • node 12.16

  • Check this box to trigger a request for Renovate to run again on this repository

The automated release is failing 🚨

🚨 The automated release from the alpha branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the alpha branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

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.