2

将使用 ParcelJS 构建的 react 应用程序迁移到 Typescript/React,我遇到了一些环境变量问题。实际上,这个问题似乎只影响错误输出,因为环境变量(URL,在<a>标签中使用)在网页上正常工作。

这是终端输出:

/Users/---/Projects/---/---/src/cart/index.tsx(xxx,xxx)
Cannot find name 'process'.
126 |       method: "post",
127 |       url: `${process.env.URL}/checkout`,
    |               ^^^^^^^
128 |       data: cart,

我尝试了几种方法,因为import * as process from "process"不能解决问题:

Could not find a declaration file for module 'process'.
'./node_modules/process/index.js' implicitly has an 'any' type.
Try `npm install @types/process` if it exists or add a new 
declaration (.d.ts)     file containing `declare module 'process';`
  > 6 | import * as process from "process";
  |                          ^^^^^^^^^

但是,如果我尝试输出有效的变量:

const ENV = process.env.MIDDLEWARE_URL;
console.log('ENV', ENV);

浏览器输出:

ENV http://localhost:3000

最后,我不知道这是 Parcel 问题还是 TSConfig 问题。有任何想法吗 ?

4

3 回答 3

3

在 Node.js TypeScript 开发中,@types/node包应该用于特定于节点的声明,包括process. 它不适合浏览器,因为它可能与 Node.js 环境除了process全局之外没有任何共同之处。

process内置模块导入在 Node.js 中是多余的,当然不应该在浏览器中使用,因为没有这样的模块(即使有shim 模块,它也不需要process.env)。

如果process由客户端脚本中的捆绑程序(ParcelJS)定义,则应在自定义类型文件(例如,typings/custom.d.ts)中为其提供类型声明:

declare const process: {
    env: {
        ENV: string;
        URL: string;
    }
}

自定义类型路径也应该在 TypeScript 配置中指定:

"typeRoots": ["./node_modules/@types", "./typings"]
于 2018-04-25T07:57:30.533 回答
1

要添加到@Kleioz 留下的评论答案,因为我仍然必须在谷歌上搜索正在发生的事情......

解决方案是添加typeRoots到 TypeScript 配置。这基本上告诉编译器 node_module 声明在哪里。如果需要,您还可以通过文件夹进行自定义声明。

{
  "compilerOptions": {
    ...
    "typeRoots": ["./node_modules/@types", "./typings"]
    ...
  }
}

./typings是您的自定义声明文件夹。

于 2019-04-26T14:34:16.423 回答
1

将正确的类型定义安装为开发依赖项可以解决问题:npm install @types/parcel-bundler --save-dev

于 2019-09-19T10:40:35.027 回答