Webpack hot module replacement not working with babel-loader and preset es2015

570 views Asked by At

Hot module replacement works with no loader, another loader, or another preset.

But it doesn't work with babel-loader and preset es2015. es2016 works. Same problem with preset "env".

Is it possible at all to use webpack hot module replacement with es2015 or env?

Below are my files:

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
      }
    ]
  },
  plugins: [
    new webpack.NamedModulesPlugin()
  ],
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

print.js

export default function printMe() {
  console.log('Updating print.js...')
}

index.html

<html>
  <head>
    <title>Output Management</title>
  </head>
  <body>
    <script src="./bundle.js"></script>
  </body>
</html>

package.json

  ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server --inline --hot"
  },
  ...

index.js

import _ from 'lodash';
import printMe from './print.js';

function component() {
  var element = document.createElement('div');
  var btn = document.createElement('button');

  // Lodash, now imported by this script
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  btn.innerHTML = 'Click me and check the console!';
  btn.onclick = printMe;

  element.appendChild(btn);

  return element;
}

let element = component(); // Store the element to re-render on print.js changes
document.body.appendChild(element);

if (module.hot) {
  module.hot.accept('./print.js', function() {
    console.log('Accepting the updated printMe module!');
    document.body.removeChild(element);
    element = component(); // Re-render the "component" to update the click handler
    document.body.appendChild(element);
  })
}

.babelrc

{ "presets": ["es2015"] }
1

There are 1 answers

0
leyou On BEST ANSWER

Found the solution.

Put this in .babelrc to disable module syntax transformation.

{ "presets": [['es2015', { modules: false }]] }