解决未捕获的语法错误:意外的标记'<' in Next.js App Deployed on AWS S3 statically

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

我的 Next.js Web 应用程序遇到了问题,该应用程序是通过 AWS S3 静态部署的。该应用程序在我的计算机上完美运行。然而,在其他人的设备上,出现 Uncaught SyntaxError: Unexpected token '<' error appears in the webpack-{hash} file, which is set with the content-type application/javascript. And 304 Moved Permanently occured when webpack file loads

我在 Chrome 开发者工具中检查了禁用缓存,或者删除了出现问题的计算机上的缓存,然后错误消失了。尽管如此,建议用户清除缓存并不是一个可行的解决方案。怀疑与缓存相关的问题,我采取了一些措施:

  • 配置S3存储桶的静态网站托管以提供index.html以响应404或403错误。
  • 在 next.config.js 中将 maxMemoryCacheSize 设置为 0。
  • 修改了部署脚本以将 Cache-Control 标头设置为 no-cache。
"scripts": {
    "build": "next build",
    "deploy": "npm run build && aws s3 sync ./out s3://{my bucket} --delete --metadata-directive REPLACE --cache-control \"no-cache, no-store, must-revalidate\" --profile={my profile}"
}

尽管做出了这些努力,问题仍然存在,用户别无选择,只能手动清除缓存。

我将 next.config.js 全部包含在下面,因为我怀疑可能有我忽略的相关配置:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})
const Dotenv = require('dotenv-webpack')
const withPlugins = require('next-compose-plugins')
const { patchWebpackConfig } = require('next-global-css')

const webpackConfig = (config, options) => {
  const prod = process.env.NODE_ENV === 'production'
  config.plugins.push(new Dotenv({ silent: true }))
  if (process.env.CYPRESS === 'true') {
    //Allows importing the global.css file
    patchWebpackConfig(config, options)
  }
  config.module.rules.push({
    test: /\.svg$/,
    use: [
      {
        loader: '@svgr/webpack',
        options: {
          svgoConfig: {
            plugins: [
              {
                // Enable figma's wrong mask-type attribute work
                removeRasterImages: false,
                removeStyleElement: false,
                removeUnknownsAndDefaults: false,
                // Enable svgr's svg to fill the size
                removeViewBox: false,
              },
            ],
          },
        },
      },
    ],
  })
  // absolute path
  config.resolve.modules.push(__dirname)
  return {
    ...config,
    mode: prod ? 'production' : 'development',
    devtool: prod ? 'hidden-source-map' : 'eval',
    plugins: [...config.plugins],
  }
}

const nextConfig = {
  maxMemoryCacheSize: 0,
  reactStrictMode: false,
  output: 'export',
  compress: true,
  typescript: {
    ignoreBuildErrors: true,
  },
  eslint: {
    ignoreDuringBuilds: true,
  },
  compiler: {
    styledComponents: true,
    emotion: true,
    removeConsole: {
      exclude:
        process.env.NODE_ENV === 'production'
          ? ['warn', 'error', 'group', 'groupEnd']
          : ['warn', 'error', 'log', 'info', 'debug', 'group', 'groupEnd', 'time', 'timeEnd'],
    },
  },
  transpilePackages: ['@mui/system', '@mui/material', '@mui/icons-material'],
  modularizeImports: {
    '@mui/material': { transform: '@mui/material/{{member}}' },
    '@mui/material/styles': { transform: '@mui/material/styles/{{member}}' },
    '@mui/icons-material': {
      transform: '@mui/icons-material/{{member}}',
    },
    '@mui/styles': {
      transform: '@mui/styles/{{member}}',
    },
    '@mui/lab': {
      transform: '@mui/lab/{{member}}',
    },
    lodash: {
      transform: 'lodash/{{member}}',
    },
  },
  webpack: webpackConfig,
}

module.exports = withPlugins([withBundleAnalyzer({})], nextConfig)

任何人都可以建议一个不需要用户清除缓存的替代解决方案吗?

reactjs amazon-s3 webpack next.js cache-control
1个回答
0
投票

当您的 JavaScript 资源被请求,但服务器(在本例中为 S3)返回 HTML 时,通常会发生这种情况 - 通常是

index.html
(以 <) instead of the JS file. As you mentioned, error on different devices hints a caching issue either at the browser level or potentially at a CDN level if you're using one in front of S3 (like CloudFront). If you are using CloudFront you might need to invalidate the cache after deploying new versions of your files. You can automate this as part of your deployment script.

开头)
aws cloudfront create-invalidation --distribution-id YOUR_DISTRIBUTION_ID --paths "/*"
© www.soinside.com 2019 - 2024. All rights reserved.