【问题标题】:Nextjs config for JSX file typeJSX 文件类型的 Nextjs 配置
【发布时间】:2023-01-31 00:39:11
【问题描述】:

我创建了一个 Next 13 应用程序,我在其中安装了一个包 @viral-loops/widgets

安装包后,当我运行应用程序时,出现以下错误

error - ./node_modules/@viral-loops/widgets/dist/react/Widget.jsx
Module parse failed: Unexpected token (34:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
|   return (
>     <>
|       {props.ucid ? (
|         <form-widget ucid={props.ucid} popup={props.popup} />

这是我的 next.config.js

module.exports = {
  webpack(config, { isServer }) {
    const prefix = config.assetPrefix ?? config.basePath ?? '';
    config.module.rules.push(
      {
        test: /\.svg$/,
        use: ['@svgr/webpack', 'url-loader'],
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'url-loader',
          },
        ],
      },
      {
        test: /\.(mp4|webm|mov|ogg|swf|ogv)$/,
        use: [
          {
            loader: require.resolve('file-loader'),
            options: {
              publicPath: `${prefix}/_next/static/videos/`,
              outputPath: `${isServer ? '../' : ''}static/videos/`,
              name: '[name]-[hash].[ext]',
            },
          },
        ],
      },
    );
    return config;
  },
  images: {
    disableStaticImages: true,
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.ctfassets.net',
        pathname: '**',
      },
    ],
  },
  sassOptions: {
    includePaths: [
      path.join(__dirname, 'styles'),
      path.join(__dirname, 'styles/variables.scss'),
    ],
    prependData: '@import "./styles/variables.scss";',
  },
  compilerOptions: {
    baseUrl: '.',
    paths: {
      '@/components/*': ['components/*'],
    },
  },
};

我尝试在 next.config.js webpack 中设置如下所示的 babel-loader

module.exports = {
  webpack(config, { isServer }) {
    const prefix = config.assetPrefix ?? config.basePath ?? '';
    config.module.rules.push(
      **{test: /\.(js|jsx)$/, use: 'babel-loader'}**,

返回如下所示的新错误

Syntax error: Support for the experimental syntax 'jsx' isn't currently enabled (34:5):

  32 |
  33 |   return (
> 34 |     <>
     |     ^
  35 |       {props.ucid ? (
  36 |         <form-widget ucid={props.ucid} popup={props.popup} />
  37 |       ) : null}

Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to the 'presets' section of your Babel config to enable transformation.

我不确定我必须在 Nextjs 应用程序中的何处添加 @babel/preset-react。

【问题讨论】:

    标签: javascript reactjs webpack next.js server-side-rendering


    【解决方案1】:

    Next.js 无法从 node_modules 目录转译 .jsx/css/scss 文件。

    您可以使用next-transpile-modules。但是,它已被弃用。

    因为只有一个组件存在此问题。您可以在项目根目录中的组件目录中创建该组件的副本并使用该组件。

    // @components/Widget
    
    import * as React from "react";
    import { useEffect } from "react";
    
    export default function Widget(props) {
      function loadViralLoops() {
        const SCRIPT_SRC = "https://app.viral-loops.com/widgetsV2/core/loader.js";
        const scriptExists = document.head.querySelector(
          `script[src="${SCRIPT_SRC}"]`
        );
        if (scriptExists) {
          return Promise.resolve();
        }
        return new Promise((resolve, reject) => {
          const script = document.createElement("script");
          script.src = SCRIPT_SRC;
          script.onload = resolve;
          script.onerror = reject;
          document.head.appendChild(script);
        });
      }
    
      useEffect(() => {
        loadViralLoops().then(() => {
          const ViralLoops = globalThis["ViralLoops"];
          console.debug("[VL] -> load ViralLoops script", ViralLoops);
        });
      }, []);
    
      useEffect(() => {
        console.debug("[VL] -> set props.ucid", props.ucid);
      }, ["[VL] -> set props.ucid", props.ucid]);
    
      return (
        <>
          {props.ucid ? (
            <form-widget ucid={props.ucid} popup={props.popup} />
          ) : null}
        </>
      );
    }
    
    Widget.defaultProps = {};
    
    

    【讨论】:

      【解决方案2】:

      尝试在项目级别创建文件.babelrc,并添加此配置并安装添加的 deps,

      {
        "presets": ["next/babel", "@babel/preset-react"],
        "plugins": ["@babel/plugin-transform-react-jsx"]
      }
      

      【讨论】:

        猜你喜欢
        • 2023-01-31
        • 2018-07-01
        • 2016-03-25
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        • 2016-09-17
        • 2021-05-13
        • 2022-11-28
        相关资源
        最近更新 更多