webpack / webpack-dev-server

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.
MIT License
7.78k stars 1.43k forks source link

webpack-dev-server stops watching files for changes on .js syntax error #3175

Closed Darkzarich closed 3 years ago

Darkzarich commented 3 years ago

Code

const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const ESLintPlugin = require('eslint-webpack-plugin')

const isProd = process.env.NODE_ENV === 'production'
const isDev = !isProd

const filename = (ext) =>
  isDev ? `bundle.${ext}` : `bundle.[fullhash].${ext}`

module.exports = {
  context: path.resolve(__dirname, 'src'),
  mode: 'development',
  entry: ['@babel/polyfill', './index.js'],
  output: {
    filename: filename('js'),
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  resolve: {
    extensions: ['.js'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@core': path.resolve(__dirname, 'src/core'),
    },
  },
  devtool: isDev ? 'source-map' : false,
  devServer: {
    port: 8080,
    hot: isDev,
    watchContentBase: true,
  },
  plugins: [
    new ESLintPlugin(),
    new HTMLWebpackPlugin({
      template: 'index.html',
      filename: 'index.html',
      minify: {
        removeComments: isProd,
        collapseWhitespace: isProd,
      },
    }),
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'src/favicon.ico'),
          to: path.resolve(__dirname, 'dist'),
        },
      ],
    }),
    new MiniCssExtractPlugin({
      filename: filename('css'),
    }),
  ],
  target: 'web',
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
    ],
  },
}

deps:

{
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "@babel/eslint-parser": "^7.13.14",
    "@babel/preset-env": "^7.13.12",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^8.1.0",
    "cross-env": "^7.0.3",
    "css-loader": "^5.2.0",
    "eslint": "^7.23.0",
    "eslint-config-google": "^0.14.0",
    "eslint-webpack-plugin": "^2.5.3",
    "html-webpack-plugin": "^5.3.1",
    "mini-css-extract-plugin": "^1.4.0",
    "sass": "^1.32.8",
    "sass-loader": "^11.0.1",
    "webpack": "^5.31.0",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "v3.11.2"
  },
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "normalize.css": "^8.0.1"
  }
}

index.js

console.log('working!')
cosole.log('working!') // trigger an error

Expected Behavior

webpack-dev-server successfully refreshes the page or places in changes

Actual Behavior

A syntax error breaks watching files and webpack-dev-server stops showing any new changes (but compiles them, terminal tells this) until the page is refreshed manually with F5

snitin315 commented 3 years ago

Can you try with webpack-dev-server@beta.2

Darkzarich commented 3 years ago

Can you try with webpack-dev-server@beta.2

I can't use watchContentBase option with the latest version (or it's just not documented) since it was removed before, without this if I change index.html somehow I don't see any changes so I have to use an older version

snitin315 commented 3 years ago

I think you need to use watchFiles option. https://github.com/webpack/webpack-dev-server/blob/e80976320d21f43e0512375d3811c8b09e705007/lib/options.json#L493

alexander-akait commented 3 years ago

Can you create reproducible test repo?

Darkzarich commented 3 years ago

I think you need to use watchFiles option. https://github.com/webpack/webpack-dev-server/blob/e80976320d21f43e0512375d3811c8b09e705007/lib/options.json#L493

@snitin315 This works, thank you.

I installed the latest version which is v4.0.0-beta.2 and it works just fine for the problem I described but there is a new problem

@alexander-akait https://github.com/webpack/webpack-dev-server/issues/3168 - here you said that

HMR and [contenthash] in mini-css-extract-plugin is not supported

But apparently the Refused to apply style from 'http://localhost:8080/bundle.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. error is still present even with hot: false and any hashing in naming turned off.

I will link my repo, it's fairly small so you can use it to reproduce: https://github.com/Darkzarich/sheets-project-training/tree/feature/basic-markup (this very branch only). In index.js try to remove the last parenthesis in console.log('working!!!').

alexander-akait commented 3 years ago

Yep, reproduced

alexander-akait commented 3 years ago

Bug, we need to set optimization.emitOnErrors: false when hmr enabled by default, workaround:

optimization: {
  emitOnErrors: false
}
snitin315 commented 3 years ago

@alexander-akait it should be done by webpack or webpack-dev-server?

alexander-akait commented 3 years ago

I need investigate, WIP on this

alexander-akait commented 3 years ago

Bug on webpack side due caching emitting logic and output.clean, reported

DelliriumX commented 3 years ago

Any news on this? I have recently rewired my entire project from scratch again only to find this now being an issue, I am unsure if I did it wrong or its just an error on the lib's side of things? For me it just never even watches at all, without syntax error either.

alexander-akait commented 3 years ago

You can avoid using output.clean right now, reported

DelliriumX commented 3 years ago

You can avoid using output.clean right now, reported

Care to elaborate just a bit, I am not sure where to set this option / I am not certain I use it. My webpack.config doesn't but I do use the CleanWebpackPlugin. Should I just disable that, or do something else?

devServer: {
      contentBase: path.resolve(__dirname, 'dist'),
      watchContentBase: true,
      https: true,
      host: '0.0.0.0',
      disableHostCheck: true,
      port: process.env.PORT || 8001,
      openPage: `https://localhost:${process.env.PORT || 8001}`,
      historyApiFallback: true,
      stats: 'errors-only',
      overlay: true,
    },
alexander-akait commented 3 years ago

Can you provide example/reproducible test repo?

DelliriumX commented 3 years ago

Can you provide example/reproducible test repo?

I can try to mock something up but will take some time, as the entire thing is super convoluted, give me 10 minutes or so to try to scrape from where I am and get it up as a new repo

DelliriumX commented 3 years ago

I tried making it on the sandbox but I can't for the death of me make it run, if you can figgure it out, be my guest: https://codesandbox.io/s/webpack-sample-ub8ue?file=/webpack.config.js

alternatively, find it on my github: https://github.com/DelliriumX/webpack-reload-clone

It is a bit convoluted, but I've cut away a lot of the custom build thing out of it so some things might not make much sense, still doesn't work. I am not sure if my start script (package-json) or devServer config is correct, but it refuses to reload, I am open to suggestions.

alexander-akait commented 3 years ago

@DelliriumX you need https://github.com/pmmmwh/react-refresh-webpack-plugin plugin and set hot: true for hot reloading react components

DelliriumX commented 3 years ago

@DelliriumX you need https://github.com/pmmmwh/react-refresh-webpack-plugin plugin and set hot: true for hot reloading react components

Thing is, I don't want hot, I want full page refreshes...

This setup (without hot: true) was working in wp4.x.x, dev server automatically watched for file changes (I didn't even have to have watchContentBase enabled - i just ran it with --watch and it did full page refreshes on file changes), but now it simply refuses to watch for file changes at all - I've also noted that it compiles twice at start, not sure if that has anything to do with it.

I get this kind of output: (node:17216) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API i 「wdm」: Compiled successfully. i 「wdm」: Compiling... i 「wdm」: wait until bundle finished: /externals-insight.node_modules_r.js i 「wdm」: wait until bundle finished: /externals-insight.node_modules_s.js i 「wdm」: wait until bundle finished: /core-insight.js i 「wdm」: Compiled successfully.

And it does recompile, just doesn't refresh the page

DelliriumX commented 3 years ago

@alexander-akait I've further reduced the clutter in that repo I've made, if you pull again you should have an easier time. This is now super-bare-bones, yet it still doesn't page-refresh. Should I open a separate issue or are the two related?

alexander-akait commented 3 years ago

It is fixed in webpack-dev-server@4-beta, we have the watchFiles option

DelliriumX commented 3 years ago

It is fixed in webpack-dev-server@4-beta, we have the watchFiles option

Any chance you'd shed some light on how to "translate" this config I am currently using, into the v4beta compatible one, or direct me to a place where I could find some migration-guide or docs?

 devServer: {
      // contentBase: path.resolve(__dirname, 'dist'),
      contentBase: './dist', // same location as all other files (basically output.path)
      hot: false, // i used to have it work without this, but im putting it here just in case
      watchContentBase: true, // i used to have it work without this, but im putting it here just in case
      https: true,
      host: '0.0.0.0',
      disableHostCheck: true,
      port: process.env.PORT || 8001,
      openPage: `https://localhost:${process.env.PORT || 8001}`,
      historyApiFallback: true,
      stats: 'errors-only',
      overlay: true,
    },

From what I could gather on the changelog quite a lot has changed, though I've not managed to find anything related to how the watchFiles you mentioned should be setup, is it just a boolean (true) ? Lastly, how would I include the v4beta into my package json?

Sorry if I am too much of a bother, not really too experienced with these sorts of things.

alexander-akait commented 3 years ago

Please rename contentBase to static and set watchFiles: 'src/**/*.jsx' (maybe other value), disableHostCheck rename to firewall: false, openPage rename to open, overlay is true by default now, remove stats and set it on top property, you can sue this stats: process.env.WEBPACK_SERVE? 'errors-only' : 'normal'

DelliriumX commented 3 years ago

Sorry it took a while to respond, was hospitalized. I think I managed to do, to an extent what you suggested. Got a question, when you say watchFiles: 'src/**/*.jsx' what does this do exactly? Do I need to specify all the files to watch? What about .js, .scss, .html? Can I use regex? Do I specify an array of strings ? That is a first one, but the second one is more bothersome, my devConfig is as follows now (per your suggestion):

devServer: {
      static: './dist',
      watchFiles: 'src/**/*.jsx',
      hot: false,
      watchContentBase: true,
      https: true,
      host: '0.0.0.0',
      firewall: false,
      port: process.env.PORT || 8001,
      open: `https://localhost:${process.env.PORT || 8001}`,
      historyApiFallback: true,
    },

and I get this error:

[webpack-cli] Invalid configuration object. Object has been initialized using a configuration object that does not match the API schema.
 - configuration has an unknown property 'before'. These properties are valid:
   object { bonjour?, client?, compress?, dev?, firewall?, headers?, historyApiFallback?, host?, hot?, http2?, https?, liveReload?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, public?, setupExitSignals?, static?, transportMode?, watchFiles? }

I am assuming its related to some plugin? Not sure if it helps, here is what I am using: NodePolyfillPlugin, HtmlWebpackPlugin, MiniCssExtractorPlugin, VirtualModulesPlugin, ErrorOverlayPlugin, DefinePlugin, Dotenv,

alexander-akait commented 3 years ago

before -> onBeforeSetupMiddleware, you can use any glob in watchFiles, i.e. watchFiles: 'src/**/*',

DelliriumX commented 3 years ago

But I don't have any before in the config, what am I missing here?

alexander-akait commented 3 years ago

@DelliriumX What is version you are use?

DelliriumX commented 3 years ago
    "webpack": "^5.33.2",
    "webpack-cli": "^4.6.0",
      "webpack-dev-server": "^4.0.0-beta.2",
alexander-akait commented 3 years ago

I think problem in ErrorOverlayPlugin, you don't need this plugin

DelliriumX commented 3 years ago

Okay that finnally got it working, though it is not:

  1. opening the right page, it opens 0.0.0.0:8000 even though my open: https://localhost:${process.env.PORT || 8001}, setting
  2. doesn't show error overlay at all
  3. watchFiles is configured as src/**/*.jsx but it watches for changes in files which are not in source, nor .jsx as well (though in this particular case, that is good for me, but thought I'd mention it - still not really sure if this is watching the source files or all the dependencies that those files "consume"
alexander-akait commented 3 years ago

doesn't show error overlay at all

overlay is enabled by default

DelliriumX commented 3 years ago

doesn't show error overlay at all

overlay is enabled by default

just ends up with a blank white page, console has the errors though

alexander-akait commented 3 years ago

console has the errors though

Can you show me?

DelliriumX commented 3 years ago

Do you want a VoIP or should i post a picture?

edit: here you go: image

also here is how the log looks like (yet it opens 0.0.0.0:8000 instead of localhost): image

alexander-akait commented 3 years ago

@DelliriumX it is feature, we will improve this in future, overlay don't show error from dev tools, but we will improve it

DelliriumX commented 3 years ago

@alexander-akait I used to use this one, since it has a nice preview, but it is now causing issues because of before as you mentioned, here is a link: https://github.com/smooth-code/error-overlay-webpack-plugin

How about the open thing, any reason you see why it doesn't open the right page?

alexander-akait commented 3 years ago

@Darkzarich fixed by https://github.com/webpack/webpack/pull/13276, update webpack to 5.36.2 :star: , feel free to feedback, sorry for delay

alexander-akait commented 3 years ago

@DelliriumX Please avoid using other issues for questions and problems not related to original, it is bad

How about the open thing, any reason you see why it doesn't open the right page?

You can setup any location to open, what is the problem with open? What is right page? We are open localhost if it is possible. You have problem with code as you can see in your screenshot, we have other issues to show console errors in overlay.

Anyway if you thinking we have somewhere bug, please open the new issue using the issue template an describe problem