node.js - 如何使用 webpack 节点 API 执行编译后的代码?
问题描述
这是我所拥有的:
#!/usr/bin/env node
const webpack = require('webpack');
const config = require('./webpack.config');
const compiler = webpack(config);
const express = require('express');
const app = express();
const os = require('os');
const Chalk = require('chalk');
const Path = require('path');
const networkInterface = process.platform === 'win32' ? 'Ethernet' : 'eth0';
const ip = os.networkInterfaces()[networkInterface].find(x => x.family === 'IPv4').address;
const port = 3000;
// https://webpack.js.org/api/node/
// https://github.com/webpack/webpack-dev-middleware/blob/master/lib/index.js
// https://github.com/webpack/webpack-dev-middleware
const watcher = compiler.watch({
aggregateTimeout: 250,
poll: 50,
ignored: /\bnode_modules\b/
}, (err, stats) => {
const elapsed = stats.endTime - stats.startTime;
console.log(`Recompiled in ${elapsed}ms`)
// How to run the compiled JS ?
})
let interrupted = false;
process.on('SIGINT', () => {
if(!interrupted) {
interrupted = true;
console.log('\b\bShutting down...');
watcher.close(() => {
console.log('Webpack watcher stopped.')
});
server.close(() => {
console.log('Express server stopped.')
});
} else {
console.log('\b\bForcing shut down');
process.exit(2);
}
});
const server = app.listen(port, '0.0.0.0', () => {
console.log(`Listening on ${Chalk.blue(`http://${ip}:${port}`)}`);
})
当观察者运行回调时,我的 JS 应该准备好执行了。我怎样才能做到这一点?该对象中应该有一些东西stats
,只是不确定要寻找什么,因为它很大。
例如,我可以获得如下输出文件名:
const assetsByChunkName = stats.toJson().assetsByChunkName;
const outputPath = stats.toJson().outputPath;
const main = Path.join(outputPath, assetsByChunkName.main);
但它不在磁盘上。如何使用 webpack 的假文件系统阅读它?或者我什至需要阅读它,内存中的输出源是否在某处?我想我只是通过它eval()
?
解决方案
我想出了一些似乎可行的方法:
const watcher = compiler.watch({
aggregateTimeout: 250,
poll: 50,
ignored: /\bnode_modules\b/
}, (err, stats) => {
if(err) {
console.error(err);
return;
}
console.log(stats.toString({
chunks: false, // Makes the build much quieter
colors: true, // Shows colors in the console
stats: 'minimal',
}));
router = eval(stats.compilation.assets['main.js'].source()).default;
})
唯一的问题是,只要源文件中存在语法错误,它就会退出。
推荐阅读
- flutter - 弯曲的导航包在点击时重建页面
- tensorflow - 如何通过 ImageDataGenerator 在 Kaggle/Colab 上使用 TPU?
- javascript - 如何删除画布html中的点?
- reactjs - 在第二次单击时导出图形时获取属性“导出”未定义
- google-cloud-platform - Terraform GCP 数据目录策略标签
- python - 在 Python 中使用 Numpy 进行字节交换
- laravel - Swagger UI requestInterceptor 抛出“Cannot set property 'X-CSRF-TOKEN' of undefined”错误
- loops - Rust 中迭代和操作的最佳/惯用方式是什么
- c# - 为什么实体框架 FindFirstOrDefault 返回 ExecutionException 而不是 null
- oracle - 在 oracle 中允许来自 SSRS 的多个值