我使用 TypeScript 构建了一个 React 组件,该组件使用 cytoscape(以及其types)作为无头模型。我的目标是创建一个 NPM 包,以便我可以直接在其他项目中导入它。
我的库:
- 当我将 cytoscape.js 作为静态资源导入到我的 index.html 中时工作
- 但是,当我在新的 es6 应用程序中
npm install
我的组件时,它不起作用:Uncaught ReferenceError: cytoscape is not defined at new WbsLayout
。尽管在安装我的组件时 cytoscape 已自动安装到 node_modules。
Typescript源代码
WbsLayout.tsx:
export class WbsLayout {
//...
public cy: Cy.Core;
constructor(graph: any, Options?: Options) {
this.cy = cytoscape({ // <-- Works or fails, see cases #1 and #2 explained above
headless: true,
elements: graph
});
//...
}
//...
}
请注意,我在组件源代码中没有任何地方导入cytoscape(或任何类似的方式),因为我似乎不需要使用Typescript和cytoscape类型定义的方式使我的组件与在html中导入的cytoscape一起工作。也许这是一个NPN软件包的问题...
一个简单的React组件,接收WbsLayout属性。Wbs.tsx:
cytoscape的类型定义(仅相关部分)
declare namespace Cy {
//...
interface Core { }
//...
interface Static {
(options?: Cy.CytoscapeOptions): Core;
(extensionName: string, foo: string, bar: any): Core;
version: string;
}
}
declare module "cytoscape" {
export = cytoscape;
}
declare var cytoscape: Cy.Static;
Webpack 2配置
Wbs.tsx
、WbsLayout.tsx
等文件会使用Webpack 2打包成@nodeject/wbs-react
:
module.exports = {
entry: {
'test/index': './src/test.tsx',
'dist/index': './src/index.tsx'
},
output: {
filename: "./[name].js",
libraryTarget: 'umd',
library: 'wbs-react',
umdNamedDefine: true
},
devtool: "source-map",
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
node: {
fs: "empty",
child_process: "empty"
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.tsx?$/,
loader: "ts-loader"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
]
},
externals: {
"react": {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
"react-dom": {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
"cytoscape": {
root: 'Cy',
commonjs2: 'cytoscape',
commonjs: 'cytoscape',
amd: 'cytoscape'
},
"chai": {
root: 'chai',
commonjs2: 'chai',
commonjs: 'chai',
amd: 'chai'
}
}
};
tsconfig.json
{
"compilerOptions": {
"outDir": "./temp/",
"sourceMap": false,
"noImplicitAny": true,
"module": "commonjs",
"target": "es2015",
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"jsx": "react"
},
"exclude": [
"node_modules",
"dist",
"temp",
"test"
]
}
新的es6应用程序源代码
import React from 'react';
import ReactDOM from 'react-dom';
import {Wbs, WbsLayout} from '@nodeject/wbs-react';
let graph = {
nodes: [
{ data: { id: '1' } },
{ data: { id: '1.1', parent: '1' } }
],
edges: [
{ data: { id: 'e1', source: '1', target: '1.1' } }
]
};
layout: new WbsLayout(graph); // <-- Fails here (case #2)
ReactDOM.render(<Wbs layout={layout}/>, document.querySelector('#wbs_example'));
import * as cytoscape from "cytoscape";
应该可以工作。 - SaravanaWbsLayout.tsx
中添加,但在同一位置(this.cy = cytoscape({ .....})
)出现了Uncaught TypeError: cytoscape is not a function
错误。 - Greg Forelmodule
目标更改为es2015
,将moduleResolution
选项更改为node
并将allowSyntheticDefaultImports
选项设置为true
吗? - Daniel Rosenwasser