Webpack bundle ENOENT:没有这样的文件或目录fs.readdirSync

isu*_*use 1 node.js webpack webpack-2

我们想创建在AWS Lambda上运行的微应用程序.我们正在调查web​​pack 2.但是,我们有遗留代码,用于fs.readdirSync获取文件/模块名称列表以生成模块列表.执行捆绑包时,我们收到错误,Error: ENOENT: no such file or directory, scandir '/innerLib'因为webpack不知道fs.readdirSync(path.resolve(__dirname, 'innerLib'));在文件中执行lib/lib.js并在捆绑时间内解析文件名数组.

我们可以使用wepback采用哪些方法,而无需对遗留代码进行重大更改.我在下面和github中包含了一个简单的例子

webpack.config.js

var path = require( 'path' );
var webpack = require( 'webpack' );

module.exports = {
  context: __dirname,
  entry: ['./index.js'],
  output: {
    filename: 'bundle.js',
  },
  target: 'node',
}
Run Code Online (Sandbox Code Playgroud)

index.js

const  lib = require('./lib/lib.js');

lib.getModuleList((err, modules) => console.log(modules));
Run Code Online (Sandbox Code Playgroud)

LIB/lib.js

const fs = require('fs');
const path = require('path');
let moduleList = [];
let list = fs.readdirSync(path.resolve(__dirname, 'innerLib'));

exports.getModuleList = getModuleList;

function getModuleList(callback) {
  return callback(null, moduleList);
}

list.forEach(filename => {
  moduleList.push({
    name: filename
  });
});
Run Code Online (Sandbox Code Playgroud)

LIB/innerLib/a.js

console.log('a lib loaded');
Run Code Online (Sandbox Code Playgroud)

LIB/innerLib/b.js

console.log('b lib loaded');
Run Code Online (Sandbox Code Playgroud)

小智 7

你的问题是__dirname解决问题/.要使其与webpack一起使用,请设置:

node: {
  __dirname: true
}
Run Code Online (Sandbox Code Playgroud)

在你的webpack.config.js中.添加之后,您的捆绑包对我来说很好.