"require" 未定义 - Sveltekit 使用 TypeScript

3

我在Svelte项目中的.ts文件中同时使用了importrequire语法,但不知道为什么会出现以下错误:

require is not defined

我想知道是否有我所不知道的东西,或者是我错过了一些简单的东西?

tsconfig.json:

{
    "compilerOptions": {
        "moduleResolution": "node",
        "module": "commonjs",
        "lib": ["dom", "es2015", "esnext"],
        "target": "es5",
        /**
            svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript
            to enforce using \`import type\` instead of \`import\` for Types.
            */
        "importsNotUsedAsValues": "error",
        "isolatedModules": true,
        "resolveJsonModule": true,
        /**
            To have warnings/errors of the Svelte compiler at the correct position,
            enable source maps by default.
            */
        "sourceMap": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "baseUrl": ".",
        "allowJs": true,
        "checkJs": true,
        "paths": {
            "$lib/*": ["src/lib/*"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.ts", "src/**/*.svelte"]
}

sveltekit 配置:

import preprocess from 'svelte-preprocess'
import ssr from '@sveltejs/adapter-static'

/** @type {import('@sveltejs/kit').Config} */
export default {
  preprocess: [
    preprocess({
      defaults: {
        style: 'postcss'
      },
      postcss: true
    })
  ],

  kit: {
    adapter: ssr(),
    target: '#svelte'
  }
}

5
在SvelteKit中不应使用require,只有import是有效的语法。 - Stephane Vanraes
许多流行的库实际上仍在使用它(例如axios),使用vite/Sveltekit构建将创建一个在浏览器中抛出"require未定义"的脚本。 - Clément Renaud
1个回答

2
这与Svelte构建期间Typescript转译有关。当我仅使用“import”样式导入和Svelte + Typescript时,就会出现这种情况。由于某些内部配置错误,Typescript可能会将“import”转译为“require()”。这也只会发生在某些npm库/模块中。
来自Svelte(而不是Typescript)Github上同一问题的一个被接受的(虽然不完美)答案提供了安装给定依赖项(对我来说是dotenv)作为devDependency而不是通常的浏览器端dep的建议。这对我起作用了。原因是Svelte和Sveltekit必须内部包含几个不同的构建步骤,其中包括vite和rollup。显然有些东西没有正确地转换导入,但这不是你作为前端Svelte开发人员需要担心的事情。
希望他们能就此发布更多指导,但我在“require”相关问题和Svelte方面发现的普遍智慧是将其尝试为dev dependency。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接