Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何变更一个非相关文件但引发 webpack 重新构建 #7

Open
soda-x opened this issue Oct 12, 2017 · 1 comment
Open

如何变更一个非相关文件但引发 webpack 重新构建 #7

soda-x opened this issue Oct 12, 2017 · 1 comment
Labels

Comments

@soda-x
Copy link
Owner

soda-x commented Oct 12, 2017

在调试环境中我们通常会有如下需求:

更改一个非 webpack 构建 assets 内容,但希望引发重新构建。

这个场景就比如小程序中的 [page].json

以往我们的做法比较绕,大致可以归结为:

  • server 通过子进程的方式启动
  • 需要监听的文件通过诸如 chokidar 来实现监听
  • 监听文件变更后重启子进程

嗯,没毛病

但是这一次看 webpack watch 实现,让我对 watch 整体实现有了非常全面的了解。

如果仔细读过文章,可以知道 webpack 的监听是发生在 compile 之后的

_done(err, compilation) {
  ...
	const stats = compilation ? this._getStats(compilation) : null;
  ...
	this.compiler.applyPlugins("done", stats);
	...
	if(!this.closed) {
		this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies);
	}
}

另外 webpack 监听的内容发生变更终将引发新的 compile 过程,这个过程可以在文章 webpack watch 实现 的手稿笔记中,查看蓝色部分的回调链路。

带着这样的思路,我给出了一个假设:

compile 之后,只要保证 compilation 中涵盖了额外的内容,那么额外文件变更也会引入重新 compile 过程。

比较庆幸的是在读 watch 机制的时候,大致看了下 webpack 的事件机制。 这一块后续必须要研读,非常具有借鉴意义。

在时间机制中有一个事件是 after-compile 就琢磨着,我就在这个时机修改下是否就可以了呢?

wala

于是就有了这个插件

extra-watch-webpack-plugin

插件实现非常简单,可以自行前往如上链接查看源码。

接下来大概说下如何使用这个插件吧

安装

npm install --save extra-watch-webpack-plugin

可选参数

  • files: string or array, defualt [], attach extra files to webpack's watch system

  • dirs: string or array, defualt [], attach extra dirs to webpack's watch system

Usage

// webpack.config.js
import ExtraWathWebpackPlugin from 'extra-watch-webpack-plugin';
......
{
  plugins: [
    new ExtraWathWebpackPlugin({
      fies: [ 'path/to/file' ],
      dirs: [ 'path/to/dir' ]
    }),
  ],
}
@soda-x soda-x added the webpack label Oct 12, 2017
@jin5354
Copy link

jin5354 commented Oct 24, 2017

webpack/webpack-dev-server#34 这里曾经有过相关讨论
如果某个文件没有显式的被 require,但是被某个 loader 引入使用了,也可以在 loader 中使用

this.addDependency(filePath)

来把该文件纳入 webpack 的依赖收集中,并且热更新什么的都运作完美。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants