使用 webpack 构建 NodeJs:无法在异步函数之外使用关键字“await”

问题描述 投票:0回答:1

我使用webpack构建nodejs(“type”:“module”)项目。 该项目包含以下文件。

import { readdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { parse as parsePath, dirname } from 'path';

const modules = await Promise.all(
  readdirSync(dirname(fileURLToPath(import.meta.url))).map(async (e, i) => {
    return new Promise(async (resolve) => {
      const pinfo = parsePath(e);
      if (pinfo.name !== 'index' && pinfo.name !== 'references') {
        const _modules = (await import(`./${pinfo.base}`)).default;

        resolve(_modules);
      } else {
        resolve({});
      }
    });
  })
);

使用语句“node index.js”它可以正常工作。 但是当使用 webpack 构建“webpack --config webpack.config.production.cjs”时,我收到错误:“不能在异步函数之外使用关键字 'await'”。

我尝试使用“@babel/plugin-transform-runtime”修复错误,但没有成功。 下面是我的 webpack.config.development.cjs 文件

const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const TerserPlugin = require('terser-webpack-plugin');

const _ = require('lodash');

const { NODE_ENV = 'production' } = process.env;

module.exports = {
  devtool: 'source-map',
  entry: [
    // "@babel/polyfill",
    './src/index',
  ],
  output: { path: path.join(__dirname, 'dist'), filename: 'server.js' },
  mode: NODE_ENV,
  watch: NODE_ENV === 'development',
  target: 'node',
  node: {
    __filename: true,
    __dirname: true,
    fs: 'empty',
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              babelrc: false,

              presets: ['@babel/env'],
              plugins: [
                [
                  '@babel/plugin-transform-runtime',
                  {
                    regenerator: true,
                  },
                ],
              ],
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
  },
  plugins: [new webpack.NamedModulesPlugin()],

  optimization: {
    minimizer: [
      new TerserPlugin({
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {
          compress: {
            drop_console: false,
          },
        },
      }),
    ],
    splitChunks: {
      chunks: 'all',
      hidePathInfo: false,
      minSize: 10000,
      maxAsyncRequests: Infinity,
      maxInitialRequests: Infinity,
    },
  },
  performance: {
    hints: 'warning', // enum
    maxAssetSize: 200000, // int (in bytes),
    maxEntrypointSize: 400000, // int (in bytes)
    assetFilter: function (assetFilename) {
      // Function predicate that provides asset filenames
      return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
    },
  },
};
javascript webpack build
1个回答
0
投票

就我而言,花了我几个月的时间,但它是 package.json 中的一个随机前端包,我从来没有想到我必须删除或更新它。就我而言,它是@mongo 嵌入图表

© www.soinside.com 2019 - 2024. All rights reserved.