Giter Club home page Giter Club 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 @soda/friendly-errors-webpack-plugin --save-dev

Basic usage

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

var FriendlyErrorsWebpackPlugin = require('@soda/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

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

Stargazers

ULTRA9MA avatar  avatar 新木 avatar 我搁这敲代码呢 avatar Asım Tahir avatar tanghc avatar  avatar ueqt avatar pseudovector avatar Eleven avatar tuntun avatar Saranraj avatar Evace avatar zqy233 avatar  avatar Vaughan Rouesnel avatar XueDong Wang avatar C avatar Waylon avatar wander avatar Damien Golding avatar watsonhaw avatar Haitao Lee avatar Septorange avatar 一水 Seeker avatar Valentin Gurkov avatar Prashis avatar Dan avatar shuisheng avatar Gin avatar 浩明1999 avatar  avatar Kiter avatar yliu avatar Mehdi avatar zoujia avatar  avatar jaskang avatar 伊撒尔 avatar Surmon avatar wubaiqing avatar Mario avatar

Watchers

James Cloos avatar  avatar  avatar

friendly-errors-webpack-plugin's Issues

Depends on vulnerable versions of strip-ansi

Getting this from npm audit fix:

# npm audit report

ansi-regex  >2.1.1 <5.0.1
Severity: moderate
 Inefficient Regular Expression Complexity in chalk/ansi-regex - https://github.com/advisories/GHSA-93q8-gq69-wqmw
fix available via `npm audit fix --force`
Will install @soda/[email protected], which is a breaking change
node_modules/ansi-regex
  strip-ansi  4.0.0 - 5.2.0
  Depends on vulnerable versions of ansi-regex
  node_modules/strip-ansi
    @soda/friendly-errors-webpack-plugin  >=1.8.0
    Depends on vulnerable versions of strip-ansi
    node_modules/@soda/friendly-errors-webpack-plugin

I think it just needs strip-ansi dependency updated to ^6 but haven't tested.

为什么配置了之后感觉没有反应呢

请教一下,我已经是使用的最简单的配置了,但是加入之后一点都没有,下面是我所有的webpack配置了

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const child_process = require("child_process");
const ESLintPlugin = require("eslint-webpack-plugin");
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");

module.exports = (_, argv) => {
  const { mode } = argv;

  process.env.NODE_ENV = mode; // .eslintrc.js中需要访问

  // 环境变量
  const env = {
    NODE_ENV: JSON.stringify(mode),

    // app TITLE
    REACT_APP_WEBSITE_NAME: JSON.stringify("React Or Antd"),

    // commitHash
    REACT_APP_Commit_Hash: JSON.stringify(
      child_process.execSync("git show -s --format=%H").toString().trim()
    ),

    // 是否开启 mockapi
    REACT_APP_MOCK: true,

    // 打包时间(启动时间)
    REACT_APP_Build_Date: JSON.stringify(
      (() => {
        const nowDate = new Date();
        return `${`${nowDate.getFullYear()}-${
          nowDate.getMonth() + 1
        }-${nowDate.getDate()} ${nowDate.getHours()}:${nowDate.getMinutes()}:${nowDate.getSeconds()}`}`;
      })()
    ),
  };

  const devServer = {
    historyApiFallback: true,
    port: 8080,
    open: false, // 是否自动打开浏览器
    hot: true, // 是否开启热更新
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
  };

  return {
    mode,
    entry: "./src/index.js",
    devtool: mode === "production" ? false : "eval",
    devServer,
    output: {
      publicPath: "/",
      filename: "[name].[hash:8].js",
      path: path.resolve(__dirname, "dist"),
      clean: true, // 清除dist文件
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          loader: "babel-loader",
        },
        {
          test: /\.css$/i,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|jpg|gif|svg)$/,
          use: [
            {
              loader: "url-loader",
              options: {
                limit: 8192, // 8kb以下转base64
                name: "images/[name].[hash:8].[ext]", // 文件名格式
              },
            },
          ],
        },
      ],
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
      extensions: [".js", ".jsx", ".css"],
    },
    plugins: [
      new FriendlyErrorsWebpackPlugin({
        compilationSuccessInfo: {
          messages: ["哈哈哈哈哈哈"],
          notes: ["123456789"],
        },
      }),

      // 设置环境变量
      new webpack.DefinePlugin({ "process.env": env }),

      new HtmlWebpackPlugin({ template: "./public/index.html" }),

      // 执行eslint校验
      new ESLintPlugin({ emitWarning: true }),

      // 打印编译进度
      new webpack.ProgressPlugin(),
    ],
  };
};

1681659308658

[Docs] Update logging section

I found the "Turn off errors" config to be confusing. I'm not using express, so it doesn't apply in my case. Also I think it's for an older version of webpack.

With webpack 5, the old logging config is obsolete, we must use infrastructureLogging instead.

This works:

module.exports = {
  //...
  infrastructureLogging: {
    level: 'error',
  },
};

I'm using "error" rather than "none". But the output is the same in both cases anyway.

That docs section should be updated to show the config above, to avoid confusion. Thanks.

Support for VS Code tasks background beginsPattern/endsPattern

VS Code supports monitoring background watch tasks by defining a regex pattern to match a message line when compilation starts and another one for when compilation ends. Messages between those two lines will be checked for problems using the problemMatcher patterns. This allows it to pick up problems for the problems view and mark whether the background watch task succeeded or failed, it has a canned problemMatcher configuration for tsc --watch which can be used to see how this should work. (Also VS Code's own committed tasks for watching VS Code own source also have such patterns defined
The problem is that @soda/friendly-errors-webpack-plugin doesn't output any message after it goes idle, and after the reported problems, instead you get the compilation ended message before the ES Lint/Build problem report, and no specific message when the background TS type checking ends. There needs to be a messages to anchor the beginsPattern/endsPattern so as to properly support VS Code problem matchers.

See vuejs/vue-cli#7073

Can you help me with a webpack custom plugin?

I have tried to write a custom plugin for my project using webpack 5

I cant use the webpack dev server on my project because is on PHP, then I want to write a plugin that open the browser when the first compilation ends

This is my example, but it does nothing

const open = require('open'); 
const myUrl = 'localhost/project-2' 
// docs https://webpack.js.org/contribute/writing-a-plugin/#creating-a-plugin 
// example https://medium.com/finnovate-io/make-webpack-exit-on-compilation-errors-16d2eec03391 
class OpenBrowserPlugin { 
  apply(compiler) { 
    compiler.hooks.done.tapAsync('MyPlugin', async function (stats, callback) { 
      await open(myUrl, { app: { name: 'google chrome', arguments: ['--incognito'] } }); 
      console.log('will open browser'); 
      callback(); 
    }); 
  } 
} 

module.exports = OpenBrowserPlugin;

Greetings

TypeError: file.split is not a function

 ERROR  TypeError: file.split is not a function
TypeError: file.split is not a function
    at removeLoaders (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/formatters/defaultError.js:23:22)
    at displayError (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/formatters/defaultError.js:10:21)
    at /my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/formatters/defaultError.js:39:20
    at Array.reduce (<anonymous>)
    at format (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/formatters/defaultError.js:38:6)
    at format (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/core/formatErrors.js:12:33)
    at Array.map (<anonymous>)
    at formatErrors (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/core/formatErrors.js:15:21)
    at FriendlyErrorsWebpackPlugin.displayErrors (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/friendly-errors-plugin.js:111:5)
    at doneFn (/my/path/node_modules/@soda/friendly-errors-webpack-plugin/src/friendly-errors-plugin.js:52:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/my/path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:18:1)
    at AsyncSeriesHook.lazyCompileHook (/my/path/node_modules/tapable/lib/Hook.js:154:20)
    at onCompiled (/my/path/node_modules/webpack/lib/Compiler.js:271:21)
    at /my/path/node_modules/webpack/lib/Compiler.js:681:15
    at eval (eval at create (/my/path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:22:1)
    at runMicrotasks (<anonymous>)
  • @soda/friendly-errors-webpack-plugin: 1.8.0
  • webpack: 4.46.0

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.