use*_*862 6 javascript google-chrome module typescript reactjs
我有一个生成 React 组件的简单模块:
// index.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
....
ReactDOM.render(......);
Run Code Online (Sandbox Code Playgroud)
react 和 react-dom 位于 node_modules\@types 目录中。
我使用 TypeScript 编译器将其编译为 .js 文件。该 .js 文件包含一个模块(因为导入)。我将其加载到 .html 页面中:
<script type="module" src="./js/Views/Home/index.js"></script>
Run Code Online (Sandbox Code Playgroud)
这会编译,我得到智能感知和类型检查。但是 Chrome(版本 66)现在在控制台中抛出一个错误,说
(index):1 Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".
Run Code Online (Sandbox Code Playgroud)
我尝试了这些选项:
1) 环境变量
// this works for both compiler and browser, but doesn't give me type checking or intellisense
declare var ReactDOM: any;
declare var React: any;
Run Code Online (Sandbox Code Playgroud)
2)根本没有声明
根据https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types,这将从当前目录、父目录等中的 node_modules 中获取任何 @types 声明)这听起来不错,但它给了我编译器错误:
'ReactDOM' refers to a UMD global, but the current file is a module. Consider adding an import instead.
Run Code Online (Sandbox Code Playgroud)
3) 三重斜线指令
/// <reference path="../../node_modules/@types/react-dom/index.d.ts" />
Run Code Online (Sandbox Code Playgroud)
把它放在文件的顶部也会产生编译器错误
'ReactDOM' refers to a UMD global, but the current file is a module. Consider adding an import instead.
Run Code Online (Sandbox Code Playgroud)
4) 在 tsconfig.json 文件中指定类型
// Added to tsconfig.json, compilerOptions element
"types": [ "ReactDOM", "React" ]
Run Code Online (Sandbox Code Playgroud)
编译器现在会抛出大量“(TS) Duplicate identifier ....”错误消息。
5)直接导入.d.ts文件
import * as React from "../../node_modules/@types/react/index.d.ts";
import * as ReactDOM from "../../node_modules/@types/react-dom/index.d.ts";
Run Code Online (Sandbox Code Playgroud)
这给了我编译器错误:
An import path cannot end with a '.d.ts' extension. Consider importing '../../node_modules/@types/react/index' instead.
Run Code Online (Sandbox Code Playgroud)
6) 直接导入 .d.ts 文件,但去掉 .d.ts 扩展名
import * as React from "../../node_modules/@types/react/index";
import * as ReactDOM from "../../node_modules/@types/react-dom/index";
Run Code Online (Sandbox Code Playgroud)
这编译。但是浏览器现在抛出错误消息:
index.tsx:1 GET http://localhost:8400/js/node_modules/@types/react/index 404 (Not Found)
index.tsx:2 GET http://localhost:8400/js/node_modules/@types/react-dom/index 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何在浏览器要加载的模块中导入类型信息?
| 归档时间: |
|
| 查看次数: |
4201 次 |
| 最近记录: |