How after building the dist folder in Webpack, move the bundle.js and css file into the statics folder?

20,142

Solution 1

This config is saving the *.js and *.css to the static folder.

 output: {
 // the output bundle
 filename: '[name].[hash].js',
 // saves the files into the dist/static folder
 path: path.resolve(__dirname, 'dist/static'),
 // set static as src="static/main.js as relative path
 publicPath: 'static/'
 },

With the HtmlWebpackPlugin you can generate a html file from a template. With this config in the Webpack plugins section the index.html is saved to the dist. folder with the correct path to the *.js and *.css.

plugins: [
   // is only working with npm run build
   new HtmlWebpackPlugin({
    title: '',
    // save index.html one director back from the output path
    filename: '../index.html',
    template: 'index.template.ejs',
    hash: false
   }),
  ],

index.template.ejs

<html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
</head>
<body>
</body>
</html>

Results in

<html>
 <head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title> 
  </title>          
  <link href="static/main.css" rel="stylesheet">
 </head>    
  <body>    
   <script type="text/javascript" src="static/main.js"></script>
  </body>    
</html>

enter image description here

Solution 2

Your output.path is incorrect. It should be path.resolve(__dirname, 'dist', 'static').

And since now your output.path points to dist/static, set publicPath back to /.

Share:
20,142
Leon Gaban
Author by

Leon Gaban

Investor, Powerlifter, Crypto investor and global citizen You can also find me here: @leongaban | github | panga.ventures

Updated on July 05, 2022

Comments

  • Leon Gaban
    Leon Gaban almost 2 years

    When I run my npm run build or npm run build-dev

    enter image description here

    It creates the index.html and manage2.bundle.js and manage2.css files in the root. I need to move those files into the static directory.

    So the generated index.html below will actually work, with the correct paths:

    <!doctype html>
    <html lang="en">
    <head>
        <title>Manage2</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="description" content="The TickerTags backend manage app">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300|Source+Sans+Pro:200,600" rel="stylesheet">
        <link rel="icon" type="image/x-icon" href="static/favicon.ico">
    <link href="/static/manage2.css" rel="stylesheet"></head>
    <body>
        <div id="manage2"></div>
    <script type="text/javascript" src="/static/manage2.bundle.js"></script></body>
    </html>
    

    How is this acomplished? webpack.config below

    const fs = require('fs');
    const webpack = require('webpack')
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    const CopyWebpackPlugin = require("copy-webpack-plugin");
    const path = require("path");
    const dist = path.resolve(__dirname, "dist");
    const src = path.resolve(__dirname, "src");
    const environment = process.env.NODE_ENV;
    
    const stream = fs.createWriteStream("src/services/environment.js");
    stream.once('open', function(fd) {
      stream.write('const env = "'+environment+'"\n');
      stream.write('export default env');
      stream.end();
    });
    
    module.exports = {
      context: src,
      entry: [
        "./index.js"
      ],
      output: {
        path: dist,
        filename: "manage2.bundle.js",
        publicPath: '/static/',
      },
      devtool: 'source-map',
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: ["babel-loader"]
          },
          {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract({
              fallbackLoader: "style-loader",
              loader: ["css-loader", "sass-loader"],
              publicPath: dist
            })
          }
        ]
      },
      devServer: {
        hot: false,
        quiet: true,
        publicPath: "",
        contentBase: path.join(__dirname, "dist"),
        compress: true,
        stats: "errors-only",
        open: true
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: "index.html"
        }),
        new ExtractTextPlugin({
          filename: "manage2.css",
          disable: false,
          allChunks: true
        }),
        new CopyWebpackPlugin([{ from: "static", to: "static" }])
      ]
    };
    // new webpack.DefinePlugin({ env: JSON.stringify(environment) })
    

    My npm scripts

    "scripts": {
        "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
        "prod": "NODE_ENV=production webpack-dev-server -p",
        "build": "NODE_ENV=production webpack -p",
        "build-dev": "NODE_ENV=production webpack -d",
    
  • Leon Gaban
    Leon Gaban almost 7 years
    When I did that, my localhost:8080 no longer works when I npm run dev. Cannot GET / also inside of my dist folder when I run npm run build I have static inside of static
  • Doodlebot
    Doodlebot almost 7 years
    Why is the devServer publicPath: ""? The documentation says it should always start and end with a forward slash.webpack.js.org/configuration/dev-server/#devserver-pub‌​licpath-
  • Doodlebot
    Doodlebot almost 7 years
    Also, you may need to modify the devserver contentBase to include the static folder. I believe the dist folder is considered the working directory so it shouldn't need to be included. contentBase: path.join(__dirname, "static")