【问题标题】:Gatsby Unhandled Runtime Error is stating that process is not definedGatsby Unhandled Runtime Error 说明未定义进程
【发布时间】:2021-11-22 19:53:44
【问题描述】:

在 StackOverflow 上的以下帖子中似乎提出了与此非常相似的问题:firstly heresecondly herethirdly here 我已遵循这些建议并使用流程更新了我的 devDependencies 并添加了更新我的 gatsby -node.js 文件在我的根目录中,建议使用以下代码:


exports.modifyBabelrc = ({ babelrc }) => ({
  ...babelrc,
  plugins: babelrc.plugins.concat(['transform-regenerator']),
})

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === 'build-html') {
    actions.setWebpackConfig({
      module: {
        rules: [{ test: /react-spring-3d-carousel/, use: loaders.null() }],
      },
      plugins: [
        // fix "process is not defined" error:
        // (do "npm install process" before running the build)
        new webpack.ProvidePlugin({
          process: 'process/browser',
        }),
      ],
    })
  }
}


这是来自浏览器本身的 gatsby 的错误:

这是我的控制台显示的错误:

这是我的 OrderDetails.js 文件中引发此错误的代码:

import React, { useEffect } from 'react'
import clsx from 'clsx'
import Grid from '@material-ui/core/Grid'
import Chip from '@material-ui/core/Chip'
import Button from '@material-ui/core/Button'
import Typography from '@material-ui/core/Typography'
import SwipeableDrawer from '@material-ui/core/SwipeableDrawer'
import useMediaQuery from '@material-ui/core/useMediaQuery'
import Hidden from '@material-ui/core/Hidden'
import { makeStyles } from '@material-ui/core/styles'
import OrderDetailItem from './OrderDetailItem'

const useStyles = makeStyles(theme => ({
  drawer: {
    height: '100%',
    width: '30rem',
    backgroundColor: 'transparent',
    [theme.breakpoints.down('xs')]: {
      width: '100%',
    },
  },
  id: {
    fontSize: '2.5rem',
    fontWeight: 600,
    marginTop: '1rem',
    marginLeft: '1rem',
  },
  bold: {
    fontWeight: 600,
  },
  date: {
    fontWeight: 600,
    marginLeft: '1rem',
    marginBottom: '1rem',
  },
  padding: {
    padding: '1rem',
  },
  status: {
    marginLeft: '1rem',
  },
  dark: {
    backgroundColor: theme.palette.secondary.main,
  },
  light: {
    backgroundColor: theme.palette.primary.main,
  },
  prices: {
    padding: '0.5rem 1rem',
  },
  text: {
    [theme.breakpoints.down('xs')]: {
      fontSize: '1.25rem',
    },
  },
  spacer: {
    minHeight: '10rem',
  },
}))

export default function OrderDetails({ orders, open, setOpen }) {
  const classes = useStyles()
  const matchesXS = useMediaQuery(theme => theme.breakpoints.down('xs'))

  const iOS = process.browser && /iPad|iPhone|iPod/.test(navigator.userAgent)

  const order = orders.find(order => order.id === open)

  const prices = [
    { label: 'Subtotal', value: order?.subtotal },
    { label: 'Shipping', value: order?.shippingOption.price },
    { label: 'Tax', value: order?.tax },
    { label: 'Total', value: order?.total },
    {
      label: 'Payment',
      string: `${order?.paymentMethod.brand.toUpperCase()} ${
        order?.paymentMethod.last4
      }`,
    },
    { label: 'Transaction', string: order?.transaction },
  ]

  return (
    <SwipeableDrawer
      open={!!open}
      onOpen={() => null}
      onClose={() => setOpen(null)}
      anchor={matchesXS ? 'bottom' : 'right'}
      classes={{ paper: classes.drawer }}
      disableBackdropTransition={!iOS}
      disableDiscovery={iOS}
    >
      <Hidden smUp>
        <Grid
          item
          classes={{ root: classes.spacer }}
          component={Button}
          disableRipple
          onClick={() => setOpen(null)}
        />
      </Hidden>
      <Grid container direction="column" classes={{ root: classes.light }}>
        <Grid item classes={{ root: classes.dark }}>
          <Typography variant="h2" classes={{ root: classes.id }}>
            Order #
            {order?.id
              .slice(order.id.length - 10, order.id.length)
              .toUpperCase()}
          </Typography>
        </Grid>
        <Grid item container classes={{ root: classes.dark }}>
          <Grid item classes={{ root: classes.status }}>
            <Chip
              label={order?.status}
              classes={{ label: classes.bold, root: classes.light }}
            />
          </Grid>
          <Grid item>
            <Typography variant="body2" classes={{ root: classes.date }}>
              {`${order?.createdAt.split('-')[1]}/${
                order?.createdAt.split('-')[2].split('T')[0]
              }/${order?.createdAt.split('-')[0]}`}
            </Typography>
          </Grid>
        </Grid>
        <Grid item classes={{ root: classes.padding }}>
          <Typography variant="body2" classes={{ root: classes.bold }}>
            Billing
          </Typography>
          <Typography variant="body2" classes={{ root: classes.text }}>
            {order?.billingInfo.name}
            <br />
            {order?.billingInfo.email}
            <br />
            {order?.billingInfo.phone}
            <br />
            <br />
            {order?.billingAddress.street}
            <br />
            {order?.billingAddress.city}, {order?.billingAddress.state}{' '}
            {order?.billingAddress.zip}
          </Typography>
        </Grid>
        <Grid item classes={{ root: clsx(classes.dark, classes.padding) }}>
          <Typography variant="body2" classes={{ root: classes.bold }}>
            Shipping
          </Typography>
          <Typography variant="body2" classes={{ root: classes.text }}>
            {order?.shippingInfo.name}
            <br />
            {order?.shippingInfo.email}
            <br />
            {order?.shippingInfo.phone}
            <br />
            <br />
            {order?.shippingAddress.street}
            <br />
            {order?.shippingAddress.city}, {order?.shippingAddress.state}{' '}
            {order?.shippingAddress.zip}
          </Typography>
        </Grid>
        {prices.map(price => (
          <Grid
            key={price.label}
            item
            container
            justifyContent="space-between"
            classes={{ root: classes.prices }}
          >
            <Grid item>
              <Typography variant="body2" classes={{ root: classes.bold }}>
                {price.label}
              </Typography>
            </Grid>
            <Grid item>
              {price.string ? (
                <Typography variant="body2" classes={{ root: classes.text }}>
                  {price.string}
                </Typography>
              ) : (
                <Chip
                  label={`$${price.value?.toFixed(2)}`}
                  classes={{ label: classes.bold }}
                />
              )}
            </Grid>
          </Grid>
        ))}
        <Grid item classes={{ root: clsx(classes.dark, classes.padding) }}>
          <Typography
            variant="body2"
            gutterBottom
            classes={{ root: classes.bold }}
          >
            Items
          </Typography>
          {order?.items.map(item => (
            <OrderDetailItem item={item} key={item.variant.id} />
          ))}
        </Grid>
      </Grid>
    </SwipeableDrawer>
  )
}

【问题讨论】:

    标签: javascript node.js reactjs webpack gatsby


    【解决方案1】:

    Gatsby 附带了他自己的 webpack 版本和实现。要覆盖/改变它,您可以使用onCreateWebpackConfig API (from gatsby-node.js)。你也可以在Adding a Custom webpack Config找到一个实现示例。

    基本上,您需要添加类似的内容(在摆脱您的 webpack.config.js 之前):

    exports.onCreateWebpackConfig = ({
      stage,
      plugins,
    }) => {
      actions.setWebpackConfig({
        plugins: [
          new webpack.ProvidePlugin({
                 process: 'process/browser',
          }),
        ],
      })
    }
    

    根据您导入 webpack 及其提供程序的方式,您可能需要直接添加 new ProvidePlugin

    【讨论】:

    • 是的,感谢您的澄清,我实际上已经更新了我的问题以包含它! @FerranBuireu
    • process.browser 已弃用。尝试使用window 代替(检查stackoverflow.com/questions/49411796/…)当然,用(typeof window !== 'undefined'
    • @FerranBuireu 你能提供一个你描述的例子吗?
    • 没有太多保密性,您只需在给定的sn-p中将process.browser替换为typeof window!== 'undefined'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2022-11-16
    • 2022-01-15
    • 2016-05-16
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多