此错误通常是由于__dirname和__filename在ES模块范围内未定义而导致的。可以通过将ECMAScript模块打包为CommonJS模块来解决该错误。将以下代码添加到webpack配置中的output部分:
module.exports = {
// ...
output: {
// ...
// 添加以下代码
libraryTarget: 'commonjs',
// ...
}
};
这将确保打包的代码是CommonJS模块,而不是ES模块。然后,在代码中使用以下代码:
const path = require('path');
const filePath = path.resolve(__dirname, 'path/to/file');
这将返回正确的文件路径。
后代码示例:
// webpack.config.js
module.exports = {
// ...
output: {
filename: 'my-bundle.js',
path: __dirname + '/dist',
libraryTarget: 'commonjs', // 将库设为CommonJS模块
}
};
// index.js
const path = require('path');
const filePath = path.resolve(__dirname, 'path/to/file');