首页 > 解决方案 > 如何使用 webpack 节点 API 执行编译后的代码?

问题描述

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()

标签: node.jswebpack

解决方案


我想出了一些似乎可行的方法:

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;
})

唯一的问题是,只要源文件中存在语法错误,它就会退出。


推荐阅读