javascript - Webpack 导入没有扩展名的文件在 HMR(热模块替换)中输出更改不正确

标签 javascript webpack webpack-dev-server webpack-hmr hot-module-replacement

我关注这个guide并像该指南一样编写代码。一切都好!但是,当我将 import printMe from './print.js' 更改为 import printMe from './print' 时,HMR 无法正确输出更改!

当我在 print.js 中进行如下更改时:

   export default function printMe() {
 -   console.log('I get called from print.js!');
 +   console.log('Updating print.js...')
   }

控制台应输出:正在更新 print.js...

但它输出:我被 print.js 调用!

当我第二次将“更新 print.js...”更改为“再次更新 print.js...”时,它不会更改。

以下是我的快照:

console output

但是,Module Resolution说:

  • If the path has a file extension, then the file is bundled straightaway.
  • Otherwise, the file extension is resolved using the resolve.extensions option, which tells the resolver which extensions (eg - .js, .jsx) are acceptable for resolution.

resolve-extensions还说:

Automatically resolve certain extensions. This defaults to:

extensions: [".js", ".json"]

所以,我的问题是:webpack 不能像上面所说的那样解析没有扩展名的路径吗?这是一个错误还是我做错了什么?我所做的只是将 import printMe from './print.js' 更改为 import printMe from './print '

我的环境:

  • 节点 v7.4.0
  • npm 4.0.5
  • webpack 3.4.1
  • webpack-dev-server 2.6.1
  • macOS Sierra 10.12

非常感谢!!

最佳答案

我想我知道为什么它工作不正确。

我所做的是:

src/index.js

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

// ...

if(module.hot) {
  module.hot.accept('./print.js', function() {
    console.log('Accepting the updated printMe module!');
    printMe();
  });
}

但是您应该始终使 import 的名称和 module.hot.accept 的第一个参数相同:

src/index.js

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

// ...

if(module.hot) {
  module.hot.accept('./print', function() {
    console.log('Accepting the updated printMe module!');
    printMe();
  });
}

或:

src/index.js

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

// ...

if(module.hot) {
  module.hot.accept('./print.js', function() {
    console.log('Accepting the updated printMe module!');
    printMe();
  });
}

这两种情况都可以。这可能是 webpack 作者的预期行为。但从我的 Angular 来看,这三种情况都应该有效。 :(

关于javascript - Webpack 导入没有扩展名的文件在 HMR(热模块替换)中输出更改不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45416409/

相关文章:

javascript - 使用弹出的 create-react-app 创建 SVG Sprite 组件

javascript - 使用 forEach js es2015 动态导入

reactjs - react 代码拆分 : ChunkLoadError: Loading chunk 0 failed

javascript - webpack 热模块替换不起作用

javascript - 使用 "opacityDecayVelocity"属性配置 paper-ripple

javascript - 创建复制文本并将其包围在段落中的 JS 函数

javascript - Nodejs - 在生产中的错误回调上重试相同的函数

javascript - 页面加载时 css 和 js 的最小和最大加载

ruby-on-rails - Vue with Rails (webpacker) 错误 : "Cannot GET/"

node.js - npm 启动时 webpack-dev-server 错误