P Varga
P Varga

Reputation: 20249

Using webpack with a .html entry

How can I webpack a web app into an output .html file, starting from a traditional input .html?

Here is a simple starting point:

index.html

<body>
  <output></output>
  <script src="./main.js"></script>
</body>

main.js

import React from "react";
document.querySelector("output").innerText = React.version;

webpack.config.js

module.exports = {
  entry: "./index.html",
  output: {
    filename: "output.html"
  },
  module: {
    rules: [
      {test: /^index\.html$/, use: [
        {loader: "extract-loader"},
        {loader: "html-loader", options: {
          attrs: ["script:src"]
        }}
      ]}
    ]
  }
}

This results in SyntaxError: Unexpected token import when processing main.js, however.

Upvotes: 20

Views: 4858

Answers (2)

Nick Jonas
Nick Jonas

Reputation: 121

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./app/index.js",
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: "svg-inline-loader",
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(js)$/,
        use: "babel-loader",
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./app/index.html",
      filename: "index.html",
    }),
  ],
  mode: process.env.NODE_ENV === "production" ? "production" : "development",
};

Upvotes: -1

JackChouMine
JackChouMine

Reputation: 1192

I hava the same issue. My solution is: create empty js file as entry and you can remove that js from output path if don't need it.

Addtionally, if you use html-webpack-plugin, you can set inject to false, the html would not inject js.

new HtmlWebpackPlugin({
  template: './views/cubes.njk', // your template
  filename: 'cubes.html',
  inject: false,
})

Upvotes: 0

Related Questions