React应用程序在本地运行,但失败,并带有意外的令牌'

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

由于两个原因,我一直在重构Webpack配置。首先,由于它已被弃用,因此要从中删除extract-text-webpack-plugin,显然我应该使用MiniCssExtractPlugin代替CSS。其次,使用splitChunks为我的代码和node_modules中的所有内容分别创建一个js和css文件似乎是一个好主意。似乎有一个很好的解决方法,它解决了一个问题,当我运行heroku push并尝试加载我的应用程序时,浏览器在控制台中抛出Uncaught SyntaxError: Unexpected token '<'错误,并且我得到了一个空白页。

  • 在开发服务器下运行良好。
  • 在heroku local下运行良好。
  • 我浏览了heroku的疑难解答页面,但没有看到版本控制,gitignore,node_modules等内容
  • 我花了今天的一半时间来探查此错误,并阅读其他堆栈溢出文章无济于事。似乎基本问题与期望js的浏览器有关,但它正在获取html。与无法正确转换有关?所以我在想我的babel配置和现在的多个文件可能正在发生某些事情,但是承认我不知道我是否处在正确的轨道上(例如vendor.build.js文件未正确转换?)。
  • 所以我怀疑问题与以某种方式分割我的输出文件有关。

关于我看来唯一不同的是我运行开发版本与生产版本时生成的文件,尽管我不确定这是否是问题的根源。显然,我在做错事,但是我对什么感到茫然。

浏览器错误的屏幕截图:

enter image description here

这是vendors.bundle.js中意外的令牌错误指向的内容。这是我应用程序的index.html文件:

here is what the unexpected token error is pointing to in vendors.bundle.js

在上面的重构练习之后,并基于以下webpack配置,开发版本生成了4个文件:

enter image description here

产品生成会生成更多文件:

enter image description here

我的webpack.config.js文件看起来像这样:

const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

process.env.NODE_ENV = process.env.NODE_ENV || "development";

if (process.env.NODE_ENV === "test") {
  require("dotenv").config({ path: ".env.test" });
} else if (process.env.NODE_ENV === "development") {
  require("dotenv").config({ path: ".env.development" });
}

module.exports = (env) => {
  const isProduction = env === "production";

  return {
    entry: ["babel-polyfill", "./src/app.js"],
    output: {
      path: path.join(__dirname, "public", "dist"),
      filename: "bundle.js",
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          default: false,
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all'
          },
        },
      },
    },
    mode: isProduction ? 'production' : 'development',
    module: {
      rules: [
        {
          loader: "babel-loader",
          test: /\.js$/,
          exclude: /node_modules/,
        },
        {
          test: /\.less$/,
            use: [
              {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  sourceMap: !isProduction,
                },
              },
              {
                loader: "css-loader",
                options: {
                  sourceMap: !isProduction,
                },
              },
              {
                loader: "less-loader",
                options: {
                  sourceMap: !isProduction,
                  modifyVars: {
                    "primary-color": "#1c88bf",
                    "link-color": "#1c88bf",
                    "border-radius-base": "2px",
                  },
                  javascriptEnabled: true,
                },
              }
            ],
        },
        {
          test: /\.s?css$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                sourceMap: !isProduction,
              },
            },
            {
              loader: "css-loader",
              options: {
                sourceMap: !isProduction,
              },
            },
            {
              loader: "sass-loader",
              options: {
                sourceMap: !isProduction,
              },
            },
          ],
        },
        {
          test: /\.(svg|eot|ttf|woff|woff2)$/,
          use: {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
              outputPath: "fonts/",
            },
          },
        },
      ],
    },
    plugins: [
      // new BundleAnalyzerPlugin(),
      new MiniCssExtractPlugin({ filename: '[name].css'}),
      new webpack.DefinePlugin({
        "process.env.FIREBASE_API_KEY": JSON.stringify(process.env.FIREBASE_API_KEY),
        "process.env.FIREBASE_AUTH_DOMAIN": JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
        "process.env.FIREBASE_DATABASE_URL": JSON.stringify(process.env.FIREBASE_DATABASE_URL),
        "process.env.FIREBASE_PROJECT_ID": JSON.stringify(process.env.FIREBASE_PROJECT_ID),
        "process.env.FIREBASE_STORAGE_BUCKET": JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
        "process.env.FIREBASE_MESSAGING_SENDER_ID": JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
      }),
    ],
    devtool: isProduction ? "source-map" : "inline-source-map",
    devServer: {
      contentBase: path.join(__dirname, "public"),
      historyApiFallback: true,
      publicPath: "/dist/",
    },
  };
};

我的.babelrc文件的价值..

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    [
      "import",
      {
        "libraryName": "antd",
        "libraryDirectory": "es",
        "style": "true"
      }
    ]
  ]
}
javascript reactjs heroku webpack babel
2个回答
0
投票

看来您对js文件的调用返回了index.html,这就是浏览器抱怨<的原因。检查是否有一些路由配置错误,如果没有任何结果,将返回index.html,然后查找为什么不匹配。


0
投票

在我的案例中,问题在于,开发和生产版本之间的上述文件名不同(请参见上面的屏幕截图)。因此,我的index.html在生产版本中引用了错误的文件名(请参阅上面的index.html脚本标记)。

我最终通过两个更改将其修复。首先,我修复了webpack配置,以为dev和prod构建输出相同的文件名。对于执行此操作的方式,这对我来说不是立即显而易见的(我不确定为什么开发人员使用vendors.bundle.js,而prod使用1.bundle.js),但最终却显得微不足道。在输出部分,我只需要将文件名参数从"bundle.js"更改为"[name].js"

新文件名:

enter image description here

webpack.config.js更改:

    output: {
      path: path.join(__dirname, "public", "dist"),
      filename: "[name].js",
    },

然后,我同时构建了dev和prod两个版本,以确认文件名现在相同。当我意识到它们是,我修改了index.html以使用之前的那两个文件名。

  <script src="/dist/vendors.js"></script>
  <script src="/dist/main.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.