Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I tried mergeWithRules in my webpack5 environment, and index.html stopped being generated by HtmlWebPackPlugin #157

Closed
AuthorProxy opened this issue Nov 9, 2020 · 6 comments

Comments

@AuthorProxy
Copy link

AuthorProxy commented Nov 9, 2020

For simple use-case:
Here how i started it:
"watch": "nodemon --exec \"cross-env NODE_OPTIONS=\"--no-deprecation\" webpack serve --progress --hot\""

/* eslint-env node */
/* eslint-disable import/first, node/no-unpublished-import */

require('@babel/register')({
  presets: ['@babel/preset-env']
});

import { mergeWithRules } from 'webpack-merge';
import WebpackBar from 'webpackbar';
import DotenvWebpackPlugin from 'dotenv-webpack';
import HtmlWebPackPlugin from 'html-webpack-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';

// import FaviconsWebpackPlugin from 'favicons-webpack-plugin';

import { PATHS } from './configs/paths';
import devConfig from './webpack.config.babel.dev';
import prodConfig from './webpack.config.babel.prod';

const imageChunkMaxSize = 20;
const getWebpackConfig = isProd => ({
  entry: {
    main: `${PATHS.src}/index.js`,
    icons: `${PATHS.src}/components/iconControls.js`
  },
  output: {
    path: PATHS.dist,
    filename: isProd ? '[name].[contenthash:8].js' : '[name].js',
    chunkFilename: isProd ? '[name].[contenthash:8].js' : '[name].js'
  },
  resolve: {
    mainFields: ['browser', 'main', 'module']
  },
  module: {
    rules: [{
      test: /\.(js(x)?)$/,
      exclude: /node_modules/,
      use: ['babel-loader?cacheDirectory', {
        loader: 'stylelint-custom-processor-loader',
        options: {
          emitWarning: true
        }
      }]
    }, {
      test: /\.(svg|eot|ttf|otf|woff(2)?)$/,
      include: PATHS.fonts,
      type: 'asset/resource',
      generator: { filename: isProd ? 'assets/fonts/[name].[contenthash:8][ext]' : 'assets/fonts/[name][ext]' }
    }, {
      test: /\.pdf$/,
      include: PATHS.pdfs,
      type: 'asset/resource',
      generator: { filename: isProd ? 'assets/pdf/[name].[contenthash:8][ext]' : 'assets/pdf/[name][ext]' }
    }, {
      test: /\.(png|gif|jp(e)?g)$/,
      include: PATHS.images,
      type: 'asset',
      parser: { dataUrlCondition: { maxSize: imageChunkMaxSize * 1024 } },
      generator: { filename: isProd ? 'assets/images/[name].[contenthash:8][ext]' : 'assets/images/[name][ext]' }
    }, {
      test: /\.svg$/,
      include: PATHS.images,
      use: [{
        loader: '@svgr/webpack',
        options: {
          svgoConfig: {
            plugins: [{
              removeViewBox: false
            }]
          }
        }
      }]
    }]
  },
  plugins: [
    new WebpackBar(),
    new DotenvWebpackPlugin({ systemvars: true }),
    new HtmlWebPackPlugin({
      base: '/',
      meta: {
        charset: 'utf-8',
        name: 'командировки, тревел-политики',
        // eslint-disable-next-line max-len
        description: 'Сервис организации командировок, финансовая отчетность, гибкие тревел-политики, интеграция с 1С, оргструктура компании',
        viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'
      },
      templateContent: ({ webpackConfig: { mode } }) => {
        const jivositeScript = mode === 'production'
          ? '<script src="//code.jivosite.com/widget.js" data-jv-id="LpGpBx0wzW" defer></script>'
          : '';

        return `<html><head>
          <link href="https://fonts.googleapis.com/css?family=Noto+Sans:400,700&display=swap&subset=cyrillic" rel="stylesheet">
          <link href="https://fonts.googleapis.com/css?family=Rubik:400,700&display=swap&subset=cyrillic" rel="stylesheet">
          <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
          <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        </head><body><div id="react-app"></div>${jivositeScript}</body>`;
      }
    }),

    // TODO [2021-01-01]: migrate to webpack5 https://github.com/jantimon/favicons-webpack-plugin/issues/234
    // new FaviconsWebpackPlugin({
    //   logo: './src/assets/images/favicon.png',
    //   favicons: {
    //     appShortName: 'hrk',
    //     icons: {
    //       android: true,
    //       appleIcon: true,
    //       appleStartup: true,
    //       coast: true,
    //       favicons: true,
    //       firefox: true,
    //       windows: true,
    //       yandex: true
    //     }
    //   }
    // }),

    new CleanWebpackPlugin({ cleanStaleWebpackAssets: false })
  ]
});

export default (_, { mode }) => {
  const isProd = mode === 'production';
  const webpackConfig = getWebpackConfig(isProd);
  return mergeWithRules()(webpackConfig, isProd ? prodConfig : devConfig);
};

this one prevent from generating index.html, but this one is working:

...
export default (_, { mode }) => {
  const isProd = mode === 'production';
  const webpackConfig = getWebpackConfig(isProd);
  return merge()(webpackConfig, isProd ? prodConfig : devConfig);
};
@AuthorProxy
Copy link
Author

It doesn't generate index.html on simple build too, without dev server

@AuthorProxy AuthorProxy changed the title I tried webpack-merge in my webpack5 environment, and index.html stop generated I tried webpack-merge in my webpack5 environment, and index.html stopped being generated by webpack server Nov 9, 2020
@AuthorProxy AuthorProxy changed the title I tried webpack-merge in my webpack5 environment, and index.html stopped being generated by webpack server I tried webpack-merge in my webpack5 environment, and index.html stopped being generated by HtmlWebPackPlugin Nov 9, 2020
@AuthorProxy AuthorProxy changed the title I tried webpack-merge in my webpack5 environment, and index.html stopped being generated by HtmlWebPackPlugin I tried mergeWithRules in my webpack5 environment, and index.html stopped being generated by HtmlWebPackPlugin Nov 9, 2020
@kristoforsalmin
Copy link
Contributor

kristoforsalmin commented Nov 12, 2020

Hi @bebraw and @AuthorProxy,

I'm experiencing a very similar issue... My use case is pretty simple — I'm replacing old merge.smart in the following way: https://github.com/kraftvaerk/generator-rammevaerk/blob/next/app/templates/_webpack.config.js.

While mergeWithRules works fine for module, it doesn't work for plugins (contents of plugins are simply replaced with []). I think the issue is in this little statement:

customizeArray: (a: any, b: any, key: Key) => {
let currentRule: CustomizeRule | Rules = rules;
key.split(".").forEach(k => {
currentRule = currentRule[k];
});
if (isPlainObject(currentRule)) {
return mergeWithRule({ currentRule, a, b });
}
return [];
}

Notice the last statement here: return [];.

When function encounters a rule (or lack thereof) that isn't a plain object, it simply returns an empty array. I changed that to return undefined; (as mentioned in README.md) to fall back to default merging and it works.

@bebraw please have a look at: https://github.com/kristoforsalmin/webpack-merge/commit/078830345cf34fd99059f10ff0b4386946bc0e6b. If that looks OK to you, then I can submit a PR. I also added a new test that covers this use case.

Might also be related to #151.

@bebraw
Copy link
Member

bebraw commented Nov 12, 2020

@kristoforsalmin Yeah, that looks correct. Please send me a PR based on your work and I'll merge. It looks like that's the right way to solve this one. You might have to apply Prettier on the code to format it.

@kristoforsalmin
Copy link
Contributor

@bebraw cool, I've just sent you a new PR. I tried to follow your coding conventions as close as I can 🙂 I tried to run Prettier, but it's not in the dependencies (you might want to include it), so I installed it globally and then run it, but it started fixing almost every file... So can you please run it yourself and fix code style, if needed. Would that be OK?

@bebraw bebraw closed this as completed in 106f586 Nov 12, 2020
@bebraw
Copy link
Member

bebraw commented Nov 12, 2020

This should be fixed in 5.4.0. Please re-open or open a new issue if you still encounter this.

@kristoforsalmin Thanks for the PR!

@bebraw
Copy link
Member

bebraw commented Nov 12, 2020

@kristoforsalmin I also fixed the Prettier issue. Now it's formatted based on Prettier 2. I changed the default branch of the project to develop so all PRs go against that in the future as I use master for releasing. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants