如何修复Webpack错误:找不到模块-on node.js(webpackEmptyContext)

时间:2020-08-31 11:54:08

标签: node.js webpack

我的webpack.config.js是:

const path = require('path');

module.exports = {
  entry: './app.ts',
  target: 'node',
  node: {
    __dirname: true
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

构建项目并运行它时,出现以下错误:

(node:51071) UnhandledPromiseRejectionWarning: Error: Cannot find module '../gather/gatherers/css-usage'
    at webpackEmptyContext (webpack:///./node_modules/lighthouse/lighthouse-core/config_sync?:2:10)
    at Function.requireGathererFr

此错误是由于我正在使用的第三方库-lighthouse引起的。

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

对于作为目标的节点,可能必须使用此软件包webpack-node-externals才能忽略node_module文件夹中的所有模块。然后声明为externals

const nodeExternals = require('webpack-node-externals');

module.exports = {
  externals: [nodeExternals()],
  // ...
};