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

webpack 5 output path error #189

Open
AuthorProxy opened this issue Nov 3, 2020 · 2 comments
Open

webpack 5 output path error #189

AuthorProxy opened this issue Nov 3, 2020 · 2 comments

Comments

@AuthorProxy
Copy link

Issue description or question

After updating to webppack5 asks for output path: [webpack-cli] TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

Webpack Config

/* eslint-env node */
/* eslint-disable import/first */

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

import path from 'path';
import dotenv from 'dotenv';
import webpack from 'webpack';

// import DotenvWebpackPlugin from 'dotenv-webpack';

import CircularDependencyPlugin from 'circular-dependency-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import HtmlWebPackPlugin from 'html-webpack-plugin';
import FaviconsWebpackPlugin from 'favicons-webpack-plugin';
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import { WindowsBalloon } from 'node-notifier';
import UnusedWebpackPlugin from 'unused-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin';
import ManifestPlugin from 'webpack-manifest-plugin';

// import { BundleStatsWebpackPlugin } from 'bundle-stats-webpack-plugin';
// import { StatsWriterPlugin } from 'webpack-stats-plugin';


// import glob from 'glob';
// import ExtractCssChunks from 'extract-css-chunks-webpack-plugin';
// import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
// import PurgecssPlugin from 'purgecss-webpack-plugin';
// import SpeedMeasurePlugin from 'speed-measure-webpack-plugin';

import { getWebpackDevServerOptions } from './configs';

// const isDev = process.env.NODE_ENV !== 'production';

const PATHS = {
  src: path.resolve(__dirname, 'src'),
  images: path.resolve(__dirname, 'src/assets/images'),
  fonts: path.resolve(__dirname, 'src/assets/fonts'),
  pdfs: path.resolve(__dirname, 'src/assets/pdf')
};

const styleLoader = {
  loader: 'style-loader',
  options: {
    insert: 'head',
    injectType: 'singletonStyleTag'
  }
};

// TODO: ExtractCssChunks
// const extractCssChunksLoader = {
//   loader: ExtractCssChunks.loader,
//   options: {
//     hmr: isDev
//   }
// };

// const moduleExtractCssChunksLoader = {
//   loader: ExtractCssChunks.loader,
//   options: {
//     // esModule: true
//     ...extractCssChunksLoader.options,
//   }
// };

const cssLoader = {
  loader: 'css-loader',
  options: {
    sourceMap: true
  }
};

const moduleCssLoader = {
  loader: 'css-loader',
  options: {

    // esModule: true,
    ...cssLoader.options,
    modules: true,
    importLoaders: 1
  }
};

const config = {
  mode: 'development',
  devtool: 'source-map',
  entry: {
    main: `${PATHS.src}/index.js`,
    icons: `${PATHS.src}/components/iconControls.js`
  },
  output: {
    // TODO: temp for clean webpack plugin and webpack 5
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[chunkhash:8].js'
  },
  resolve: {
    mainFields: ['browser', 'main', 'module'],
    alias: {
      'react-dom': '@hot-loader/react-dom'
    }
  },
  module: {
    rules: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader', {
        loader: 'stylelint-custom-processor-loader',
        options: {
          emitWarning: true
        }
      }]
    }, {
      test: /\.css$/,
      include: /\.module\.css$/,
      use: [styleLoader, /* moduleExtractCssChunksLoader, */ moduleCssLoader]
    }, {
      test: /\.css$/,
      exclude: /\.module\.css$/,
      use: [styleLoader, /* extractCssChunksLoader, */ cssLoader]
    }, {
      test: /\.(svg|eot|ttf|otf|woff|woff2)$/,
      include: PATHS.fonts,
      type: 'asset/resource',
      generator: {
        filename: 'assets/fonts/[name][ext]'
      }
    }, {
      test: /\.pdf$/,
      include: PATHS.pdfs,
      type: 'asset/resource',
      generator: {
        filename: 'assets/pdf/[name][ext]'
      }
    }, {
      test: /\.(png|gif|jpg|jpeg)$/,
      include: PATHS.images,
      type: 'asset',
      parser: {
        dataUrlCondition: {
          maxSize: 20 * 1024
        }
      },
      generator: {
        filename: 'assets/images/[name][ext]'
      }
    }, {
      test: /\.txt$/,
      type: 'asset/source'
    }, {
      test: /\.svg$/,
      include: PATHS.images,
      use: 'svg-react-loader'
    }]
  },
  optimization: {
    runtimeChunk: {
      name: 'manifest'
    },
    splitChunks: {
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }

        // TODO: ExtractCssChunks
        // styles: {
        //   test: /\.css$/,
        //   name: 'styles',
        //   chunks: 'all',
        //   enforce: true
        // }
      }

      // name: true // TODO: move to webpack 5
    }

    // TODO: split node modules
    // splitChunks: {
    //   chunks: 'all',
    //   maxInitialRequests: Infinity,
    //   minSize: 0,
    //   cacheGroups: {
    //     common: {
    //       name: 'common',
    //       minChunks: 2,
    //       chunks: 'all',
    //       reuseExistingChunk: true,
    //       enforce: true,
    //       priority: 10
    //     },
    //     vendors: {
    //       test: /[\\/]node_modules[\\/]/,
    //       name(module) {
    //         const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
    //         return `npm.${packageName.replace('@', '_')}`;
    //       },
    //       priority: 20
    //     }
    //   }
    // }

  },
  plugins: [

    new ESLintPlugin(),
    // new webpack.optimize.AggressiveMergingPlugin(),

    // TODO: wait until will be fixed
    // new DotenvWebpackPlugin({ systemvars: true }),

    new webpack.DefinePlugin({
      'process.env': JSON.stringify(dotenv.config().parsed)
    }),

    new CircularDependencyPlugin({
      failOnError: false,
      exclude: /node_modules/,
      cwd: PATHS.src
    }),

    new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
    new HtmlWebPackPlugin({ template: './src/index.html' }),
    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 ExtractCssChunks({
    //   filename: '[name].[contenthash].css',
    //   chunkFilename: '[id].[contenthash].css'
    // }),
    // new PurgecssPlugin({
    //   paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true })
    // }),

    new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: ['You application is running here http://localhost:3000'],
        notes: ['Some additionnal notes to be displayed unpon successful compilation']
      },
      onErrors: (severity, errors) => {
        if (severity !== 'error') {
          return;
        }

        const error = errors[0];
        new WindowsBalloon().notify({
          title: 'Webpack compilation error',
          message: `${severity}: ${error.name}`,
          subtitle: error.file || ''
        });
      },

      clearConsole: false
    }),

    new UnusedWebpackPlugin({
      directories: [PATHS.src],
      exclude: [
        '*.spec.js',
        '*.mocks.js',
        'adapters/**/*.js',
        'utils/testUtils.js',
        'assets/images/loaders/**/*.*'
      ]
    }),

    new ManifestPlugin({
      fileName: 'manifest.mappings.js',
      writeToFileEmit: true
    })

    // TODO: migrate to webpack5
    // new BundleStatsWebpackPlugin({ baseline: true }),
    // new StatsWriterPlugin({ stats: { all: true } })
  ]
};

module.exports = env => {
  process.env.BABEL_ENV ||= env;
  if (env && env.cli) {
    global.console.log(`Running cli webpack-dev-server: ${JSON.stringify(env || 'not specified')}`);
    config.devServer = getWebpackDevServerOptions();
    config.devtool = 'cheap-source-map';
  }

  // TODO: try in webpack5, previously was [hash] error
  // const smp = new SpeedMeasurePlugin();
  const smp = null;
  return smp ? smp.wrap(config) : config;
};

Environment

Run: npx envinfo --system --binaries --npmPackages clean-webpack-plugin,webpack

System:
    OS: Windows 10 10.0.19041
    CPU: (6) x64 Intel(R) Core(TM) i5-8500 CPU @ 3.00GHz
    Memory: 3.01 GB / 31.84 GB
  Binaries:
    Node: 12.18.4 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.8 - C:\Program Files\nodejs\npm.CMD
  npmPackages:
    clean-webpack-plugin: ^3.0.0 => 3.0.0
    webpack: ^5.3.2 => 5.3.2
@drazisil
Copy link

FWIW, I'm 99% sure this is a dotenv error, if that helps any. I'm afraid I don't have a solution, yet.

@drazisil
Copy link

drazisil commented Aug 31, 2021

@AuthorProxy Get rid of the dotenv code in the plugins section and add this at the top

import Dotenv from 'dotenv';
Dotenv.config()

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

2 participants