【发布时间】:2018-09-19 11:38:50
【问题描述】:
这是我的第一个 React/Typescript/ASP.NET Core 应用,请原谅我的无知。我正在尝试从 GitHub 存储库安装一个新模块,它似乎比它应该的更复杂,但我似乎找不到解决方案。
问题:我已将 GitHub 上的 this 项目安装到我的 Web 应用程序(使用 Typescript 的 ASP.NET Core 2.0 React 应用程序)中。我现在正在尝试导入它,但每时每刻都在寻找障碍。
它类似于others,但不同的是其他人讨论自己的组件,而这是来自属于其他人的repo。
我可以理解使用导出等来更新 JS/JSX 文件以适应诸如此类的问题,但是当从另一个可能定期更新的项目中添加模块时,如何做到这一点?
步骤: 1. 安装。 npm install react-super-select --save 2. 添加到webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
const superSelect = require('react-super-select');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'main': './ClientApp/boot.tsx' },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: 'dist/'
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [
new CheckerPlugin(),
new superSelect(),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.css')
])
}];
};
-
导入到我的 .tsx 文件中:
import * as React from 'react'; 从'react-router'导入{RouteComponentProps,重定向}; 从'react'导入{ChangeEvent,Props,Key}; 导入 { formatDateInt, formatDatePeriod } from '../Dates'; 导入“同构提取”; 导入 * as ReactSuperSelect from 'react-super-select';
这是错误开始的地方。使用此设置,我收到以下错误:
TS7016 (TS) Could not find a declaration file for module 'react-super-select'. 'C:/AzTech/AzTechWebPortal/trunk/AzTechWebPortal/AzTechWebPortal/node_modules/react-super-select/lib/react-super-select.js' implicitly has an 'any' type.
Try `npm install @types/react-super-select` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-super-select';
没有@types/react-super-select 并且在查看声明文件错误时发现可以将导入更改为:
const ReactSuperSelect: any = require('react-super-select');
这不会引发错误,我可以添加到以下组件中:
class Upload_FieldMapping extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = { items: [], loading: true };
//PUT AN IF HERE TO HANDLE THIS BEING A SCHEDULE IMPORT
fetch('api/Upload/FieldMappings')
.then(response => response.json() as Promise<string[]>)
.then(data => {
this.setState({ items: data, loading: false });
}).then(data => console.log(data));
}
public render() {
type CostMap_Import = typeof CostMap_Import;
type SchedMap_Import = typeof SchedMap_Import;
let contents = this.state.loading
? <p><em>Loading...</em></p>
: Upload_FieldMapping.renderMappingsTable(this.state.items, this.props.selected === rdEV || 'undefined' ? CostMap_Import : SchedMap_Import);
return <div>{contents}</div>
}
private static renderMappingsTable(values: string[], fMaps: any) {
return <table className='table'>
<tr>
<ReactSuperSelect />
</tr>
<tr>
{Object.keys(fMaps).map(function (i: Key) {
return <li key={i}>{i}</li>
})}
</tr>
</table>
}
}
-
运行。这是我无法克服的。运行应用时,Startup.cs 中的 Configure 方法报错:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // global policy - assign here or on each controller app.UseCors("CorsPolicy"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ReactHotModuleReplacement = true }); }
错误:
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.AspNetCore.Builder.WebpackDevMiddleware.UseWebpackDevMiddleware(IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options)
at AzTechWebPortal.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\Startup.cs:line 47
Inner Exception 1:
NodeInvocationException: Cannot find module 'classnames'
Error: Cannot find module 'classnames'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\react-super-select\lib\react-super-select.js:1:2323)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
如果我需要创建声明文件,就这样吧。但是对于没有安装 @types 的项目来说,情况总是这样吗?
为了我和其他人,完成这项工作的最简单方法是什么(不放弃适当的约定)?
更新 根据评论,我安装了类名和 lodash:
npm install classnames --save
npm install lodash --save
并且错误变成了如下:
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.AspNetCore.Builder.WebpackDevMiddleware.UseWebpackDevMiddleware(IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options)
at AzTechWebPortal.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\Startup.cs:line 47
Inner Exception 1:
NodeInvocationException: Cannot read property 'controlId' of undefined
TypeError: Cannot read property 'controlId' of undefined
at new ReactSuperSelect (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\react-super-select\lib\react-super-select.js:1:4130)
at module.exports (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\webpack.config.js:28:13)
at createWebpackDevServer (C:\AzTech\AzTechWebPortal\trunk\AzTechWebPortal\AzTechWebPortal\node_modules\aspnet-webpack\WebpackDevMiddleware.js:194:31)
at createWebpackDevServer (C:\Users\EL-C\AppData\Local\Temp\emxsocle.wn2:74:50)
at C:\Users\EL-C\AppData\Local\Temp\0dd3jvzv.ill:114:19
at IncomingMessage.<anonymous> (C:\Users\EL-C\AppData\Local\Temp\0dd3jvzv.ill:133:38)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
【问题讨论】:
标签: reactjs typescript asp.net-core