Code Monkey home page Code Monkey logo

friendly-errors-webpack-plugin's Introduction

Friendly-errors-webpack-plugin

npm Build Status Build status

Friendly-errors-webpack-plugin recognizes certain classes of webpack errors and cleans, aggregates and prioritizes them to provide a better Developer Experience.

It is easy to add types of errors so if you would like to see more errors get handled, please open a PR!

Getting started

Installation

npm install friendly-errors-webpack-plugin --save-dev

Basic usage

Simply add FriendlyErrorsWebpackPlugin to the plugin section in your Webpack config.

var FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

var webpackConfig = {
  // ...
  plugins: [
    new FriendlyErrorsWebpackPlugin(),
  ],
  // ...
}

Turn off errors

You need to turn off all error logging by setting your webpack config quiet option to true.

app.use(require('webpack-dev-middleware')(compiler, {
  // ...
  logLevel: 'silent',
  // ...
}));

If you use the webpack-dev-server, there is a setting in webpack's devServer options:

// webpack config root
{
  // ...
  devServer: {
    // ...
    quiet: true,
    // ...
  },
  // ...
}

If you use webpack-hot-middleware, that is done by setting the log option to false. You can do something sort of like this, depending upon your setup:

app.use(require('webpack-hot-middleware')(compiler, {
  log: false
}));

Thanks to webpack-dashboard for this piece of info.

Demo

Build success

success

eslint-loader errors

lint

babel-loader syntax errors

babel

Module not found

babel

Options

You can pass options to the plugin:

new FriendlyErrorsPlugin({
  compilationSuccessInfo: {
    messages: ['You application is running here http://localhost:3000'],
    notes: ['Some additional notes to be displayed upon successful compilation']
  },
  onErrors: function (severity, errors) {
    // You can listen to errors transformed and prioritized by the plugin
    // severity can be 'error' or 'warning'
  },
  // should the console be cleared between each compilation?
  // default is true
  clearConsole: true,

  // add formatters and transformers (see below)
  additionalFormatters: [],
  additionalTransformers: []
})

Adding desktop notifications

The plugin has no native support for desktop notifications but it is easy to add them thanks to node-notifier for instance.

var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
var notifier = require('node-notifier');
var ICON = path.join(__dirname, 'icon.png');

new FriendlyErrorsPlugin({
    onErrors: (severity, errors) => {
      if (severity !== 'error') {
        return;
      }
      const error = errors[0];
      notifier.notify({
        title: "Webpack error",
        message: severity + ': ' + error.name,
        subtitle: error.file || '',
        icon: ICON
      });
    }
  })

API

Transformers and formatters

Webpack's errors processing, is done in four phases:

  1. Extract relevant info from webpack errors. This is done by the plugin here
  2. Apply transformers to all errors to identify and annotate well know errors and give them a priority
  3. Get only top priority error or top priority warnings if no errors are thrown
  4. Apply formatters to all annotated errors

You can add transformers and formatters. Please see transformErrors, and formatErrors in the source code and take a look a the default transformers and the default formatters.

TODO

  • Make it compatible with node 4

friendly-errors-webpack-plugin's People

Contributors

0xflotus avatar arjohnston avatar atilkan avatar christophehurpeau avatar cncolder avatar coreyleelarson avatar designbyadrian avatar epilande avatar geowarin avatar glavin001 avatar haroenv avatar lyrkan avatar michmich avatar nkzawa avatar ooflorent avatar pieh avatar pk-nb avatar racer01 avatar richardscarrott avatar sparty02 avatar sudo-suhas avatar syossan27 avatar timneutkens avatar weaverryan avatar weilinzung avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

friendly-errors-webpack-plugin's Issues

Compilation is always succesful when it should not be

For some reason my errors or warnings are not shown, and the compilation is always succesful.
I use webpack-dev-server and webpack-merge to merge two webpack configs.

Edit: Also tried with a project that uses webpack-hot-middleware and webpack-dev-middleware. There it also always compiles succesfully and does not log eslint or build errors.

base:

const baseConfig = {
  mode: 'production',
  output: {
    filename: 'static/js/[name].[hash].js',
    path: paths.resolveRoot('dist'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          cacheDirectory: true,
        },
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.svg$/,
        oneOf: [
          {
            resourceQuery: /external/,
            loader: 'url-loader',
            options: {
              limit: 10000,
            },
          },
          {
            loader: '@svgr/webpack',
          },
        ],
      },
      {
        test: /\.(jpe?g|png|gif)$/i,
        oneOf: [
          {
            resourceQuery: /external/,
            loader: 'file-loader',
            options: {
              name: 'static/[name].[ext]',
            },
          },
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'static/images/[hash].[ext]',
            },
          },
        ],
      },
      {
        exclude: [
          /\.jsx?$/,
          /\.css$/,
          /\.svg$/,
          /\.(jpe?g|png|gif)$/i,
          /\.json$/,
          /\.html$/,
          /\.ejs$/,
        ],
        loader: 'file-loader',
        options: { name: 'static/[name].[ext]' },
      },
    ],
  },
  plugins: [
    new CopyWebpackPlugin(['./public']),
    new HtmlWebpackPlugin({
      template: paths.resolveSrc('template.ejs'),
      filename: 'index.html',
      chunksSortMode: 'none',
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'all',
        },
      },
    },
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
    alias: {
      app: paths.resolveSrc(),
      common: paths.resolveSrc('components/common'),
      components: paths.resolveSrc('components'),
      config: paths.resolveSrc('config'),
      ducks: paths.resolveSrc('ducks'),
      fonts: paths.resolveSrc('static/fonts'),
      images: paths.resolveSrc('static/images'),
      modules: paths.resolveSrc('components/modules'),
      services: paths.resolveSrc('services'),
      styles: paths.resolveSrc('styles'),
      vectors: paths.resolveSrc('static/vectors'),
    },
  },
};

dev config:

const devConfig = {
  mode: 'development',
  devtool: 'eval-source-map',
  entry: {
    app: ['@babel/polyfill', paths.resolveSrc()],
  },
  devServer: {
    host: '0.0.0.0',
    port: process.env.PORT || 3001,
    hot: true,
    historyApiFallback: true,
    quiet: true,
    compress: true,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin(globals),
    new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: ['Application is running on http://localhost:3000'],
      },
    }),
  ],
};

Support MultiCompiler / MultiStats

webpack(config) returns a MultiCompiler if your config is an array of configurations and multiCompiler.plugin('done', multiStats => {}); provides MultiStats meaning this plugin could potentially receive a MultiCompiler instance.

Currently it works well with the MultiCompiler as it only uses the plugin method which is supported on the MultiCompiler.

It falls down however when interfacing with the MultiStats instance as it looks something like this:

{
    stats: [
        Stats,
        Stats
    ]
}

So it would need to get errors and warnings from each of those child Stats instances.

The other problem is it reads DONE Compiled successfully in NaNms because stats.startTime and stats.endTime don't exist on MultiStats, it'd have to be calculated from both of the child stats.

I'm not sure if this is something you want to support as it is possible to simply apply the plugin to both compilers separately but it means stdout will be flushed to twice so I think it would only show the error from one of the compilations, regardless of 'severity'. Also, the build time would only reflect one of the compilations....not sure if there would be any other implications you can think of with this approach?

As an aside, great work on the plugin -- makes all the difference during development!

recommending a different eslint-loader formatter in the docs

After looking into @babel/code-frame to improve the code-frame of eslint errors, i saw that someone already done that (maybe without @babel/code-frame).

my initial poc for showing any (not just eslint) error code frame using @babel/code-frame is: (very bad implementation but it's working)

function displayError(severity, error) {
  const locationInfo = error.message
    .split('[24m')[1]
    .split('m')[1]
    .split('[')[0]

  const [line, column] = locationInfo.split(':')

  const filePath = error.webpackError.module.resource
  const rawFileAsString = fs.readFileSync(filePath, 'utf8')

  const location = { start: { line: Number(line), column: Number(column.slice(0, column.length - 1)) } }

  const result = codeFrameColumns(rawFileAsString, location, {
    highlightCode:true // show colors in the code that we print in the terminal
  })

  console.log(result)

  return result
}

the core problem is finding the line and column numbers. we just don't have them.
we need to to give to babel and to create a link so the user can go to the error location.

when writing a eslint-formatter, you have direct access to them.

in the furure, if we can find a way to get the column and line number nicely, we can build a single solution for any kind of errors. for now, i'm not sure how so i have a solution to the eslint errors.


npm install eslint-formatter-friendly --save-dev

This is a different (non-default) eslint-loader formatter to show warnings and errors:

{
    loader: 'eslint-loader',
    options: {
      // ...
      formatter: require('eslint-formatter-friendly')
    }
}

The errors will look like this now:

instead of: (with the default eslint-loader formatter):

Cannot read property 'indexOf' of undefined

  TypeError: Cannot read property 'indexOf' of undefined
  
  - esLintError.js:7 e.originalStack.some.stackframe
    [zzz]/[friendly-errors-webpack-plugin]/src/transformers/esLintError.js:7:44
  
  - Array.some
  
  - esLintError.js:11 transform
    [zzz]/[friendly-errors-webpack-plugin]/src/transformers/esLintError.js:11:7
  
  - Array.reduce
  
  - Array.map
  
  - friendly-errors-plugin.js:86 FriendlyErrorsWebpackPlugin.displayErrors
    [zzz]/[friendly-errors-webpack-plugin]/src/friendly-errors-plugin.js:86:29
  
  - friendly-errors-plugin.js:51 Compiler.compiler.plugin.stats
    [zzz]/[friendly-errors-webpack-plugin]/src/friendly-errors-plugin.js:51:14
  
  - Tapable.js:61 Compiler.applyPlugins
    [zzz]/[tapable]/lib/Tapable.js:61:14
  
  - Compiler.js:227 onCompiled
    [zzz]/[webpack]/lib/Compiler.js:227:12
  
  - Compiler.js:480 
    [zzz]/[webpack]/lib/Compiler.js:480:13
  

error Command failed with exit code 1.

Notifications example in the readme doesn't work

The example from the readme doesn't work.

var NotifierPlugin = require('friendly-errors-webpack-plugin');
var notifier = require('node-notifier');
var ICON = path.join(__dirname, 'icon.png');

new NotifierPlugin({
    onErrors: (severity, errors) => {
      if (severity !== 'error') {
        return;
      }
      const error = errors[0];
      notifier.notify({
        title: context.pkg.name,
        message: severity + ': ' + error.name,
        subtitle: error.file || '',
        icon: ICON
      });
    }
  })
]

title property passed to the notifier.notify uses a variable context that is not defined and the whole thing fails.

I tried googling this and looking into the code but haven't came up with anything. Where is context supposed to come from?

Thanks in advance!

Change the color of dateString

Hi,

On my terminal(iTerm2 MacOS), i'm using a gray bg and the dateString is displayed in black

Is it possible to change the dateString color to blue/white/gray or add an option to choose it ?
Something like this:

new FriendlyErrorsPlugin({
    output: {
        dateString: {color: 'blue'}
    }
});

On node_modules/friendly-errors-webpack-plugin/src/output.js:54, i found this:

// Line 54:
const dateString = chalk.grey(date.toLocaleTimeString());

On github chalk depo documentation, there is no grey color !
I tried chalk.gray(date.toLocaleTimeString()) -> doesn't work !

So i change it to chalk.blue(date.toLocaleTimeString()) -> it works

Thanks

website is down

the website geowarin.github.io/friendly-errors-webpack-plugin mentioned in the package.json gives a 404

No errors when webpack config fails

When your webpack config is invalid, it won't output to the console because quiet is true, but the plugin has not been 'applied'.

Error with quiet set to to false:

$ cross-env NODE_ENV=development webpack-dev-server --inline --progress --config build-tools/config/webpack/webpack.dev.conf.js
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.output.filename: A relative path is expected. However the provided value "/asset/[name].js" is an absolute path!
   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.
   Please use output.path to specify absolute path and output.filename for the file name.
error Command failed with exit code 1.

Error with quiet set to true:

$ cross-env NODE_ENV=development webpack-dev-server --inline --progress --config build-tools/config/webpack/webpack.dev.conf.js
error Command failed with exit code 1.

Adding a log in the constructor and in the apply(compiler) { methods, only the constructor is executed.

So it seems there is a 'gap' before the plugin kicks in, where errors could happen, but don't get outputted because quiet needs to be set to true for this plugin to 'work'.

I'm not sure if there is a way to fix this, otherwise it would be good to clearly mention it in the readme/docs; when webpack exits without an error, temporarily disable the quiet mode.

does it work with typescript ?

Does it work with typescript in an angular project? if yes what should i "setup" on my webpack.config file on top of the instructions of this plugin?

support webpack4?

webpack4 has published, can u update this plugin for support webpack4?

Stylelint support

Hey, i am having a problem displaying the Stylelint errors, i am not sure if its setup issue i created.
If i use the friendly-errors-webpack-plugin enabled it wont show the stylelint errors, only the native ones :
bildschirmfoto 2017-03-01 um 22 39 54

if i disable the plugin it will display both:
bildschirmfoto 2017-03-01 um 22 43 59

how do i disable the other reporter or give stylelint the priority ? i know it might be not the right place to ask but i figured some of u might have run into the same issue.

thats my webpack.config.js:


module.exports = {
.
.
.
  module: {
    rules: removeEmpty([
      {
        test: /\.js$/,
        use: 'eslint-loader',
        enforce: 'pre', // avoid linting before babel transpile
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              minimize: false,
              autoprefixer: false,
              sourceMap: true,
              importLoaders: 1,
              url: false,
            },
          },
          {
            loader: 'postcss-loader',
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          plugins: ['syntax-dynamic-import'],
        },
      },
  plugins: {
   new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: ['You application is running here http://hajok.dev'],
      },
      clearConsole: true,
    }),
    new StyleLintPlugin({
      context: path.resolve(__dirname, 'src/scss'),
      syntax: 'scss',
    }),
 .
.
.

thats my postcss.config.js:

module.exports = {
  plugins: {
    'postcss-import': {},
    'postcss-flexbugs-fixes': {},
    'postcss-cssnext': {
      browsers: ['last 2 versions', '> 5%'],
    },
  },
};

Webpack-dev-server 'quiet: true' but errors are shown in console

When devServer flag is set to quiet: true I still see eslint errors thrown in console. Once I remove friendly-errors-webpack-plugin all errors are hidden.
Runningwebpack: 4.1.6, webpack-dev-server: 3.1.5 and friendly-errors-webpack-plugin: 1.7.0.
Is there some other magic setting missing?

Way to use this lib while piping the output to another lib.

Hi thanks for your work!

I'm using a setup built with https://github.com/jaredpalmer/backpack and it uses this library like many other build systems for webpack.

I use https://github.com/trentm/node-bunyan for server side logging since it outputs json which is easy to transport around. But for pretty printing it on the console I need to pipe the output to it, which solves the bunyan pretty printing problem but decolorizes the output of webpack/backpack. Any ideas on how to support both at the same time?

Standard Setup
image

With piping

// package.json
  "scripts": {
    "dev": "backpack | bunyan -o short",  // <-- this step
  }

image

SyntaxError: Unexpected token )

when I installed version 1.6.0, I got this following error:

vue-demo/node_modules/friendly-errors-webpack-plugin/src/formatters/moduleNotFound.js:39
  );
  ^
SyntaxError: Unexpected token )
    at Object.exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/sqrtthree/Downloads/vue-demo/node_modules/friendly-errors-webpack-plugin/src/friendly-errors-plugin.js:21:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)

I think this is because that there is a extra comma behind the last argument in line 38.

Filter warning/errors messages

Hi there, It would be great if one could filter messages like dev-server already does

something like this:

    // Filter warnings to be shown (since webpack 2.4.0),
    // can be a String, Regexp, a function getting the warning and returning a boolean
    // or an Array of a combination of the above. First match wins.
    warningsFilter: "filter" | /filter/ | ["filter", /filter/] | (warning) => true|false

Blank error when only webpackError property populated

If all the properties of the webpackError object are empty apart from webpackError property friendly-errors-webpack-plugin outputs nothing apart from the red word "Error".

I have the following webpackError outputted from the plugin: html-webpack-plugin:

{
  message: undefined,
  file: undefined,
  origin: '',
  name: undefined,
  severity: 0,
  webpackError: '  Error: Child compilation failed:\n' +
    "  Module not found: Error: Can't resolve '../foobar.html' in 'C:\\foobar':\n" +
    '  - compiler.js:79 \n' +
    '    [v1]/[html-webpack-plugin]/lib/compiler.js:79:16\n',
  originalStack: []
}

Actual Output:
Error:

Expected Output:
Error: Error: Child compilation failed Module not found: Error: Can't resolve '../foobar... etc.

As a userland fix I have added the following additionalTransformers to my config options:

additionalTransformers: [
  (webpackError) => {
    if (typeof webpackError.message === 'undefined') {
      webpackError.message = webpackError.webpackError;
    }
    return webpackError;
  },
],

New maintainers welcome: Future of the project

Hello everyone !

Next Saturday, I will be on vacation for a month so I won't be able to merge pull requests or work on the project.

It's a great opportunity to welcome new maintainers and talk about the goals of the project.
I've given write access to @christophehurpeau. Christophe, are you able to take care of the project while I'm away?

Does anyone else wants to step up and ensure bugs are fixed and versions published?
@timneutkens ? @nkzawa ?

I'd like to give you write access to the npm repo as well. I'm not sure how to do it though.

Project goals

My main goal for this project is to keep supporting nextjs, it is the biggest and coolest project depending on us.

Support for exotic use cases and loaders like sass, stylus or less are nice-to-haves but not a priority.

Thoughts and ideas ?

Loader string attached to file path

when applying loaders with few options, the output of the file path is usually pretty long because is holding the entire loader string with it.
Example of a warning prompt by eslint

Warning in ../blocklevel/blue-next/packages/bcli/~/babel-loader/lib?presets[]=/web/blocklevel/blue-next/packages/bcli/~/babel-preset-es2015/lib/index.js&presets[]=/web/blocklevel/blue-next/packages/bcli/~/babel-preset-stage-2/lib/index.js&plugins[]=/web/blocklevel/blue-next/packages/bcli/~/babel-plugin-transform-runtime/lib!../blocklevel/blue-next/packages/bcli/~/eslint-loader?configFile=/web/blocklevel/blue-next/packages/eslint-config-blocklevel!./src/app/page/home/home.js

Is it possible to extract only the actual file path, in this case /src/app/page/home/home.js, without its entire loader string?

Unexpected recompile when links in output is clicked

Some terminal apps can detect strings like URL or file system path and make them clickable, this plugins seems recompile when these links are clicked

Maybe it is not actually recompiling, but this behavior is really weired

jietu20180506-160404

Not showing the real missing module

2016-12-31 4 32 55

here I miss-spelled postcss-loader to postcss-loadedr, and use it with stylus-loader to import some .styl file, can we have the error log showing the real missing module inseatd of b.styl?

Cannot read property 'startsWith' of undefined

friendly-errors-webpack-plugin: "version": "1.7.0"
webpack: "version": "4.20.2"

when code require a non-exists path like:
require.context('./components', false, /[\w-]+\.vue$/);

webpack will throw an exception:

ModuleNotFoundError: Module not found: Error: Can't resolve './components' in '/Users/unightsun/workspace/js/crawler-v2/cms-server/src' at factory.create (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/webpack/lib/Compilation.js:798:10) at asyncLib.parallel (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/webpack/lib/ContextModuleFactory.js:143:23) at /Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/neo-async/async.js:2817:7 at /Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/neo-async/async.js:6783:13 at contextResolver.resolve (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/webpack/lib/ContextModuleFactory.js:118:26) at doResolve (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/Resolver.js:184:12) at hook.callAsync (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/Resolver.js:238:5) at _fn0 (eval at create (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1) at resolver.doResolve (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:37:5) at hook.callAsync (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/Resolver.js:238:5) at _fn0 (eval at create (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1) at hook.callAsync (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/Resolver.js:238:5) at _fn0 (eval at create (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:12:1) at resolver.doResolve (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:42:38) at hook.callAsync (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/enhanced-resolve/lib/Resolver.js:238:5) at _fn3 (eval at create (/Users/unightsun/workspace/js/crawler-v2/cms-server/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:42:1) resolve './components' in '/Users/unightsun/workspace/js/crawler-v2/cms-server/src' using description file: /Users/unightsun/workspace/js/crawler-v2/cms-server/package.json (relative path: ./src) Field 'browser' doesn't contain a valid alias configuration using description file: /Users/unightsun/workspace/js/crawler-v2/cms-server/package.json (relative path: ./src/components) as directory /Users/unightsun/workspace/js/crawler-v2/cms-server/src/components doesn't exist

it's dependencies is:
[ RequireContextDependency { module: null, weak: false, optional: false, loc: SourceLocation { start: [Object], end: [Object] }, options: { request: './components', recursive: false, regExp: /[\w-]+\.vue$/, mode: 'sync' }, userRequest: './components', critical: false, hadGlobalOrStickyRegExp: false, range: [ 384, 438 ] } ]

so 'friendly-errors-webpack-plugin/src/transformers/moduleNotFound.js:17':

const module = webpackError.dependencies[0].request;

will be undefined.

and then 'friendly-errors-webpack-plugin/src/formatters/moduleNotFound.js:5'

return module.startsWith('./') || module.startsWith('../');

will throw a TypeError: Cannot read property 'startsWith' of undefined

optional fix will be 'friendly-errors-webpack-plugin/src/transformers/moduleNotFound.js:17':

- const module = webpackError.dependencies[0].request;
+ const dependency = webpackError.dependencies[0];
+ const module = dependency.request || dependency.options.request;

module is undefined

in builtin formatter moduleNotFound

return module.startsWith('./') || module.startsWith('../');

module here may be undefined in some case

e.g.

function loadPage( path ) {
  return () => import( `@/pages/${ path }.vue` )
}

if alias @ is not set in webpack, it will throw module not found error, but friendly-errors-webpack-plugin didn't catch the error, and all errors will be swallowed

Config setup with multi-compiler Webpack CLI?

How should the plugin be applied in a multi-compiler setup when used with the webpack CLI? #9 does not give a clear indication on how the configs should look, and there has been no response in the closed issues on this (#16 and #8).

I even looked at the tests to try and figure it out, but they appear to use the Node API only, not the Webpack CLI.

Below is a skeleton example of what I'm working with. If I apply the friendly errors plugin to both configs I get two compilations showing different compilation times. It is especially frustrating with clearConsole: true because if the first finisher has an error and second finisher is successful, the terminal is cleared and only shows the success message.

If someone could provide some insight into this, it'd be greatly appreciated. This plugins looks like it would help out my development workflow tremendously, but it doesn't seem to work as expected with this setup.

webpack.config1.babel.js

import FriendlyErrorsPlugin from 'friendly-errors-webpack-plugin';

export default {
  entry: {
    ...
  },
  output: {
    ...
  },
  plugins: [
    new FriendlyErrorsPlugin()
  ]
}

webpack.config2.babel.js

import FriendlyErrorsPlugin from 'friendly-errors-webpack-plugin';

export default {
  entry: {
    ...
  },
  output: {
    ...
  },
  plugins: [
    new FriendlyErrorsPlugin()
  ]
}

webpack.config.babel.js

import configOne from './webpack.config1.babel';
import configTwo from './webpack.config2.babel';

export default [configOne, configTwo];

Does not work with Node.js v12

I get this error when running webpack with the plugin:

#
# Fatal error in , line 0
# Check failed: U_SUCCESS(status).
#
#
#
#FailureMessage Object: 0x7ffc4c0f7a70

webpack: 4.31.0
friendly-errors-webpack-plugin: 1.7.0
Node.js: 12.0.0

Plugin makes webpack --json output invalid

Hi,

when using friendly-errors-webpack-plugin with webpack --json the generated JSON is invalid:

 DONE  Compiled successfully in 21858ms12:59:37

{
  "errors": [],
  "warnings": [],
  "version": "2.3.2",
  "hash": "0837132c83435ec275e9",
  "time": 21858,
  "publicPath": "/",
...

Maybe you can add a check if --json flag is set and omit the compilation message? Otherwise it's impossible to pipe the webpack --json output to other tools such as webpack-bundle-size-analyzer:

$ webpack --json | webpack-bundle-size-analyzer
Error: The input is not valid JSON.

Check that:
 - You passed the '--json' argument to 'webpack'
 - There is no extra non-JSON content in the output, such as log messages.

The parsing error was:

  SyntaxError: Unexpected token D in JSON at position 1

It doesn't seem to work at all with scss

I know that the title of this report sounds very generic, but this is exactly what happens - I can see no difference in the console output when the friendly-errors-webpack-plugin is enabled.

This is the output when the plugin is disabled:
scss-disabled

And this is the output when the plugin is enabled:
scss-enabled

So, as you can see, they look the same. Is it a bug, or is it my misunderstanding of what the plugin is supposed to do? Is it supposed to work with css/scss or just with JS?

Here's my webpack config:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const SpritesmithPlugin = require('webpack-spritesmith');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    entry: [
        './src/js/app.js',
        './src/scss/app.scss'
    ],
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'js/app.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        'scss': 'vue-style-loader!css-loader!postcss-loader!sass-loader',
                    }
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                exclude: /(sprites|sprites@2x).png/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[path][name].[ext]',
                        context: './src/img/',
                        outputPath: 'img/',
                        publicPath: '../img/'
                    }
                },
                    {
                        loader: 'image-webpack-loader'
                    }
                ]
            },
            {
                test: /\.(eot|otf|ttf|woff)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[path][name].[ext]',
                        context: './src/font/',
                        outputPath: 'font/',
                        publicPath: '../font/'
                    }
                }]
            },
            {
                test: /(sprites|sprites@2x).png/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]',
                    outputPath: 'img/',
                    publicPath: '../img/'
                }
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        'css-loader',
                        'resolve-url-loader',
                        'postcss-loader',
                        'sass-loader?sourceMap'
                    ]
                })
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        },
        modules: [
            'node_modules',
            'temp' // spritesmith generated files
        ]
    },
    plugins: [
        new FriendlyErrorsWebpackPlugin(),
        new CopyWebpackPlugin([{
            context: './src/font/',
            from: '**/*',
            to: 'font/' // It's relative to ./dist
        }]),
        new ExtractTextPlugin('/css/app.css'),
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, 'src/img/sprites/'),
                glob: '*.png'
            },
            target: {
                image: path.resolve(__dirname, 'temp/sprites.png'),
                css: path.resolve(__dirname, 'temp/sprites.scss')
            },
            retina: '@2x',
            apiOptions: {
                cssImageRef: "~sprites.png"
            }
        })
    ],
    devServer: {
        historyApiFallback: true,
        noInfo: true
    },
    performance: {
        hints: false
    },
    devtool: '#eval-source-map'
};

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map';
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        })
    ])
}

And this is my package.json

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "dependencies": {
    "bootstrap": "4.0.0-alpha.6",
    "jquery": "^3.1.1",
    "lodash": "^4.17.4",
    "normalize.scss": "^0.1.0",
    "outdated-browser": "^1.0.2",
    "salvattore": "^1.0.9",
    "sassy-gridlover": "^4.0.0",
    "slick-carousel": "^1.6.0",
    "vue": "^2.2.2",
    "vue-router": "^2.3.0",
    "vue-template-compiler": "^2.2.2"
  },
  "devDependencies": {
    "autoprefixer": "^6.7.6",
    "babel-core": "^6.0.0",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.4.0",
    "babel-preset-es2015": "^6.9.0",
    "copy-webpack-plugin": "^4.0.1",
    "cross-env": "^3.2.3",
    "css-loader": "^0.27.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.10.1",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "image-webpack-loader": "^3.2.0",
    "node-sass": "^4.5.0",
    "object-fit-images": "^3.1.3",
    "path": "^0.12.7",
    "postcss-loader": "^1.3.3",
    "postcss-object-fit-images": "^1.1.2",
    "resolve-url-loader": "^2.0.2",
    "sass-loader": "^6.0.3",
    "style-loader": "^0.13.2",
    "vinyl-fs": "^2.4.4",
    "vinyl-ftp": "^0.6.0",
    "vue-loader": "^11.1.4",
    "vue-style-loader": "^2.0.3",
    "webpack": "^2.2.1",
    "webpack-build-notifier": "^0.1.13",
    "webpack-dev-server": "^2.4.1",
    "webpack-spritesmith": "^0.3.3"
  },
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack --progress --hide-modules --watch",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules",
    "deploy": "yarn run build && node deploy"
  },
  "browser": {
    "slick": "./node_modules/slick-carousel/slick/slick.js"
  },
  "browserify-shim": {
    "slick": {
      "exports": "null"
    }
  }
}

Is there anything else I can provide you with?

Remove duplicates

Some modules depend on the same thing, so the user sees results like:

These dependencies were not found in node_modules:

* js-cookie in ./path/to/something/different...
* color in ./path/to/something/different...
* mobx-react in ./path/to/something/different...
* react-component-queries in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* color in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* mobx in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* color in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* color in ./path/to/something/different...
* styled-components in ./path/to/something/different...
* styled-components in ./path/to/something/different...

Did you forget to run npm install --save for them?

A couple recommendations:

  • .filter the errors to only show one per module (that's enough).
  • Recommend npm install --save ${modules.join(" "}.
  • For bonus points, check for yarn.lock in process.cwd() and recommend yarn add ${modules.join(" "} instead.

Multi compiler

Is it possible to have a multi compiler configuration with this module?

Blank Error with Angular 5

Friendly Error doesn't seem to give errors correctly with Angular 5. It detects the error but doesn't show the error string resulting in the following.

screen shot 2018-05-02 at 10 58 05 am

File not found vs module not found

I have this code

import something from '../path/to/file';
import redux from 'redux';

But the error output is the following

These dependencies were not found in node_modules:

* ../path/to/file
* redux

Did you forget to run npm install --save for them?

It would be great if we could split this into two separate type of errors

Module not found

This dependency was not found in node_modules:

* redux

Did you forget to run npm install --save for it?

File not found

This file or directory as was not found

* ../path/to/file

For the file not found it would be quite interesting to search for that file in a one directory above and one directory below. For example for ../path/to/file we could check in ./path/to/file and ../../path/to/file. If we do something like this, then we could add that info to the output.

This file or directory as was not found

* ../path/to/file

Did you mean `../../path/to/file`?

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.