如何使用Node将webpack输出为字符串

时间:2017-02-17 02:21:31

标签: node.js webpack

我正在尝试使用Webpack捆绑一堆文件。我的节点代码中有以下内容......

  webpack({
    entry: "./src/test",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
  }, function(err, stats){
    console.log("I would like to output the created js here");
  })

这可以很好地创建一个名为bundle.js的文件,但我无法弄清楚如何以字符串形式输出。

1 个答案:

答案 0 :(得分:1)

基本上你可以做的是读取文件,然后根据需要使用它。
e.g。

import webpack from 'webpack';
const config = require('../webpack.config');

const compiler = webpack(config);

compiler.run((err, stats) => {  
    const data = stats.toJson();

    const app = data.assetsByChunkName.app[0] //here you can get the file name  
    // if you don't have chunks then you should use data.assets;

    const file = fs.readFileSync('path to your output ' + app); //read the file
    //now you can work with the file as you want.
});

//Basic webpack.config.js
module.exports = {
  devtool: 'source-map',
  entry: {
    app: 'Some path' // you can have different entries.
    entrie2 : ''
    .... more entries
  },
  output: {
    path: 'Some path'
  }
}

希望得到这个帮助。