![](/img/trans.png)
[英]Correct way of using typescript files from modules in typescript node+express project? currently throwing Error: Cannot find module
[英]Can't Find Modules Error In Yeoman Generated Express Typescript Project
我使用yeoman生成了一個快速打字稿項目,並且每次運行該應用程序時,都會得到以下ff錯誤:找不到模塊“ morgan”找不到模塊“ body-parser”找不到模塊“ cookie-parser”
但是所有這些模塊都在node_modules目錄中退出,我在Google上四處搜索,唯一能找到的是運行npm鏈接(模塊名),而在項目的根目錄沒有大括號,但問題仍然存在,我嘗試在npm install根和錯誤不會消失。 我也只在本地安裝了那些缺少的模塊,它仍然無法正常工作。
我究竟做錯了什么。
這是我的app.ts。
/// <reference path="./typings/tsd.d.ts"/>
/// <reference path="./typings/index.d.ts" />
import * as path from 'path';
import * as logger from 'morgan';
import * as express from 'express';
import * as bodyparser from 'body-parser';
import * as cookieParser from 'cookie-parser'
// Import our application router class to handle routing.
import { ApplicationRouter } from './routes/index';
// Module for the express application.
var app = express();
// Our express middleware.
app.use( logger('dev') );
app.use( bodyparser.json() );
app.use( bodyparser.urlencoded({ extended: false }) );
app.use( cookieParser() );
// Global application headers.
app.use( (req: express.Request, res: express.Response, next: Function) => {
res.header( 'Access-Control-Allow-Origin', '*' );
res.header( 'Access-Control-Allow-Method', 'GET, POST, PUT, PATCH, DELETE, OPTIONS' );
res.header( 'Access-Control-Allow-Header', 'Origin, X-Requested-With, Content-Type, Accept' );
});
// Router Module
let appRouter = new ApplicationRouter();
// Application's routes.
app.use( appRouter.getIndex() );
// Catch 404 and forward to error handler.
app.use( (req: express.Request, res: express.Response, next: Function) => {
var error: any = new Error('Not Found');
error.status = 404;
next( error );
});
// Development error handler will print stacktrace.
if ( app.get('env') === 'development' ) {
app.use( (error: any, req: express.Request, res: express.Response, next: Function) => {
return res.status( error.status || 500 );
});
}
// Production error handler prints no stacktrace to user.
app.use( (error: any, req: express.Request, res: express.Response, next: Function) => {
return res.status( error.status || 500 );
});
module.exports = app;
Typescript需要與這些模塊關聯的定義文件。 這些文件通常由社區維護,並在DefinitelyTyped Github網站上可用
從typescript 2.0開始,可以使用npm將它們添加到項目中。
例如,要為摩根安裝它們,只需運行
npm install @types/morgan
對每個模塊等等
(避免使用/// <reference path=
元標記。如果需要使定義文件可用,而npm無法提供這些定義文件(例如您自己制作的文件),只需使用tsconfig.json
文件並確定typings
目錄不會從編譯路徑除外)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.