Skip to content

Commit

Permalink
feat: hmr supports linked npm packages changes
Browse files Browse the repository at this point in the history
  • Loading branch information
zp365238 committed Jan 13, 2024
1 parent 9888812 commit bba1061
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 5 deletions.
2 changes: 1 addition & 1 deletion crates/mako/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl DevServer {
// let mut watcher = RecommendedWatcher::new(tx, notify::Config::default())?;
let mut debouncer = new_debouncer(Duration::from_millis(10), None, tx).unwrap();
let watcher = debouncer.watcher();
Watch::watch(&root, watcher)?;
Watch::watch(&root, watcher, &compiler)?;

let initial_hash = compiler.full_hash();
let mut last_cache_hash = Box::new(initial_hash);
Expand Down
24 changes: 22 additions & 2 deletions crates/mako/src/watch.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Sender;
use std::sync::Arc;

use mako_core::anyhow;
use mako_core::anyhow::{self, Ok};
use mako_core::notify::{self, EventKind, Watcher};
use mako_core::notify_debouncer_full::DebouncedEvent;

use crate::compiler::Compiler;

pub struct Watch {
pub root: PathBuf,
pub delay: u64,
Expand All @@ -14,7 +17,11 @@ pub struct Watch {

impl Watch {
// pub fn watch(root: &PathBuf, watcher: &mut notify::RecommendedWatcher) -> anyhow::Result<()> {
pub fn watch(root: &PathBuf, watcher: &mut notify::RecommendedWatcher) -> anyhow::Result<()> {
pub fn watch(
root: &PathBuf,
watcher: &mut notify::RecommendedWatcher,
compiler: &Arc<Compiler>,
) -> anyhow::Result<()> {
let items = std::fs::read_dir(root)?;
items
.into_iter()
Expand All @@ -32,6 +39,19 @@ impl Watch {
}
Ok(())
})?;

let module_graph = compiler.context.module_graph.read().unwrap();
let (dependencies, _) = module_graph.toposort();
dependencies
.into_iter()
.try_for_each(|module_id| -> anyhow::Result<()> {
let path = Path::new(&module_id.id);
if path.is_file() {
watcher.watch(Path::new(&path), notify::RecursiveMode::NonRecursive)?;
}
Ok(())
})?;

Ok(())
}

Expand Down
78 changes: 76 additions & 2 deletions scripts/test-hmr.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import assert from 'assert';
import { execSync } from 'child_process';
import { chromium, devices } from 'playwright';
import 'zx/globals';

function skip() {}

const root = process.cwd();
const tmp = path.join(root, 'tmp', 'hmr');
const tmpPackages = path.join(root, 'tmp', 'packages');
if (!fs.existsSync(tmp)) {
fs.mkdirSync(tmp, { recursive: true });
}
Expand Down Expand Up @@ -1067,6 +1069,68 @@ runTest('issue: 861', async () => {
await cleanup({ process, browser });
});

runTest('link npm packages', async () => {
await commonTest(
() => {
write(
normalizeFiles({
'/src/index.tsx': `
import React from 'react';
import ReactDOM from "react-dom/client";
import { foo } from "mako-test-package-link";
function App() {
return <div>{foo}<section>{Math.random()}</section></div>;
}
ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
`,
}),
);
writePackage(
'mako-test-package-link',
normalizeFiles({
'package.json': `
{
"name": "mako-test-package-link",
"version": "1.0.0",
"main": "index.js"
}
`,
'index.js': `
export * from './src/index';
`,
'src/index.js': `
const foo = 'foo';
export { foo };
`,
}),
);
execSync(
'cd ./tmp/packages/mako-test-package-link && pnpm link --global',
);
execSync('pnpm link --global mako-test-package-link');
},
(lastResult) => {
assert.equal(lastResult.html, '<div>foo</div>', 'Initial render');
},
() => {
writePackage(
'mako-test-package-link',
normalizeFiles({
'src/index.js': `
const foo = 'bar';
export { foo };
`,
}),
);
},
(thisResult) => {
assert.equal(thisResult.html, '<div>bar</div>', 'Second render');
fs.unlinkSync('./node_modules/mako-test-package-link');
},
true,
);
});

function normalizeFiles(files, makoConfig = {}) {
return {
'/public/index.html': `
Expand Down Expand Up @@ -1106,6 +1170,14 @@ function write(files) {
}
}

function writePackage(packageName, files) {
for (const [file, content] of Object.entries(files)) {
const p = path.join(tmpPackages, packageName, file);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, content, 'utf-8');
}
}

function remove(file) {
const p = path.join(tmp, file);
fs.unlinkSync(p);
Expand Down Expand Up @@ -1162,13 +1234,15 @@ function normalizeHtml(html) {
}

async function commonTest(
files = {},
initFilesOrFunc = {},
lastResultCallback = () => {},
modifyFilesOrCallback = () => {},
thisResultCallback = () => {},
shouldReload = false,
) {
write(normalizeFiles(files));
typeof initFilesOrFunc === 'function'
? await initFilesOrFunc()
: write(normalizeFiles(files));
await startMakoDevServer();
await delay(DELAY_TIME);
const { browser, page } = await startBrowser();
Expand Down

0 comments on commit bba1061

Please sign in to comment.