NodeJS 语法错误:无法在模块next.js外部使用import语句

nx7onnlm  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(146)

当我尝试在我的next.js项目中运行register.tsx页面时,我一直得到下面的错误。我有一个使用typescript的Next.js项目。

import React, { useState } from 'react';
    ^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1176:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

下面是我的register.tsx文件中的代码。我认为这与axios有关,但我注解了部分代码,它仍然给我同样的错误。

import React, { useState } from 'react';
import axios from 'axios';

export default function Register() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleRegister = async (e: { preventDefault: () => void; }) => {
    e.preventDefault();

    try {
      const response = await axios.post('/api/register', { email, password });
      console.log(response.data); // Registration successful, handle the response as needed
    } catch (error) {
      console.log(error.response.data); // Registration failed, handle the error as needed
    }
  };

  return (
    <div>
      <h1>Register</h1>
      <form onSubmit={handleRegister}>
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
        <button type="submit">Register</button>
      </form>
    </div>
  );
}
2wnc66cl

2wnc66cl1#

在package.json中,我添加了“type”:“模块”,它修复了这个问题。

相关问题