【问题标题】:Webpack hot module replacement not working with babel-loader and preset es2015Webpack 热模块替换不适用于 babel-loader 和预设 es2015
【发布时间】:2018-02-06 00:36:45
【问题描述】:

热模块更换在没有加载器、另一个加载器或另一个预设的情况下工作。

但它不适用于 babel-loader 和预设 es2015。 es2016 有效。 预设“env”也有同样的问题。

是否可以用 es2015 或 env 使用 webpack 热模块替换?

以下是我的文件:

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"] }

【问题讨论】:

    标签: webpack babeljs webpack-dev-server babel-loader


    【解决方案1】:

    找到了解决办法。

    把这个放在 .babelrc 中可以禁用模块语法转换。

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

    【讨论】:

      猜你喜欢
      • 2019-03-10
      • 2016-03-24
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2020-02-29
      • 2017-10-02
      • 2016-04-01
      相关资源
      最近更新 更多