未捕获的类型错误:无法读取未定义的属性“拆分”(Webpack)

时间:2021-03-23 07:58:58

标签: node.js reactjs webpack

我正在更新我的 Chrome 扩展程序(使用 Create React App),但突然出现此错误:

未捕获的类型错误:无法读取未定义的属性“拆分”

对于以下代码:

/* WEBPACK VAR INJECTION */(function(process) {
Object.defineProperty(exports, "__esModule", { value: true });
const defer_to_connect_1 = __webpack_require__(1533);
const nodejsMajorVersion = Number(process.versions.node.split('.')[0]);

错误出现在(process.versions.node.split('.')[0]的最后一行,代码由Webpack生成。

这是我的 Webpack 配置:

"use strict";

const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ManifestPlugin = require("webpack-manifest-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const paths = require("./paths");
const getClientEnvironment = require("./env");

const publicPath = paths.servedPath;

const shouldUseRelativeAssetPaths = publicPath === "./";

const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== "false";

const publicUrl = publicPath.slice(0, -1);

const env = getClientEnvironment(publicUrl);

if (env.stringified["process.env"].NODE_ENV !== '"production"') {
  throw new Error("Production builds must have NODE_ENV=production.");
}

const cssFilename = "static/css/[name].css";

const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? { publicPath: Array(cssFilename.split("/").length).join("../") }
  : {};

module.exports = {
  mode: "production",
  externals: ["dns"],
  bail: true,

  devtool: shouldUseSourceMap ? "inline-source-map" : false,

  entry: {
    app: [require.resolve("./polyfills"), paths.appIndexJs],
    content: [require.resolve("./polyfills"), "./src/content.js"],
  },
  optimization: {
    minimize: false,
  },
  output: {
    path: paths.appBuild,

    filename: "static/js/[name].js",
    chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",

    publicPath: publicPath,

    devtoolModuleFilenameTemplate: (info) =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, "/"),
  },
  resolve: {
    modules: ["node_modules", paths.appNodeModules].concat(
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),

    extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
    alias: {
      "react-native": "react-native-web",
    },
    plugins: [new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])],
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: "pre",
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve("eslint"),
            },
            loader: require.resolve("eslint-loader"),
          },
        ],
        include: paths.appSrc,
      },
      {
        oneOf: [
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve("url-loader"),
            options: {
              limit: 10000,
              name: "static/media/[name].[hash:8].[ext]",
            },
          },

          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve("babel-loader"),
            options: {
              compact: true,
            },
          },

          {
            test: /\.css$/,
            use: [{ loader: MiniCssExtractPlugin.loader }, "css-loader"],
          },

          {
            loader: require.resolve("file-loader"),

            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            options: {
              name: "static/media/[name].[hash:8].[ext]",
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),

    new webpack.DefinePlugin(env.stringified),

    new MiniCssExtractPlugin({
      filename: cssFilename,
    }),

    new ManifestPlugin({
      fileName: "asset-manifest.json",
    }),

    new SWPrecacheWebpackPlugin({
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: "service-worker.js",
      logger(message) {
        if (message.indexOf("Total precache size is") === 0) {
          return;
        }
        if (message.indexOf("Skipping static resource") === 0) {
          return;
        }
        console.log(message);
      },
      minify: true,

      navigateFallback: publicUrl + "/index.html",

      navigateFallbackWhitelist: [/^(?!\/__).*/],

      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),

    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],

  node: {
    dgram: "empty",
    fs: "empty",
    net: "empty",
    tls: "empty",
    child_process: "empty",
  },
};

我已经尝试更新依赖项,但收效甚微。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的错误,在我的 webpack.config.js 中我使用了 process.env.APP_URL.split('//')[1] 有一天我删除了 .env 文件,因为这个过程.env.APP_URL 变得未定义。 您还应该检查类似的问题,因为您也在 process.env.NODE_PATH 上使用 split