Node.js + Typescript + Webpack =找不到模块
我是新的Webpack,Node.js和Typescript,我无法configuration我的开发环境。
当运行webpack
编译我的src/server.ts
来生成/server/bundle.js
我得到这个错误:
ERROR in ./src/server.ts Module not found: Error: Can't resolve 'hapi' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/src' @ ./src/server.ts 3:11-26
该项目的架构是:
src/server.ts
:
import * as Hapi from 'hapi'; const server = new Hapi.Server();
webpack.config.js
:
const path = require('path'); module.exports = { entry: './src/server.ts', output: { filename: './server/bundle.js' }, resolve: { extensions: ['.ts'], modules: [ path.resolve('src'), path.resolve('node_modules') ] }, module: { loaders: [ { test: /.ts$/, loader: 'awesome-typescript-loader' } ] } };
package.json
:
{ "name": "nodang-api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "compile": "webpack --progress --watch", "serve": "node-dev server/bundle.js" }, "author": "", "license": "ISC", "dependencies": { "@types/hapi": "^16.0.0", "lodash": "^4.17.4" }, "devDependencies": { "awesome-typescript-loader": "^3.0.8", "tsd": "^0.6.5", "typescript": "^2.2.1", "webpack": "^2.2.1" } }
OBS:它是webpack 2
UPDATE
安装hapi
并添加.js
到webpack的解决scheme扩展和node
作为webpack的目标我得到这个与hapi模块的错误:
ERROR in ./~/hapi/lib/server.js Module not found: Error: Can't resolve 'catbox' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib' @ ./~/hapi/lib/server.js 5:15-32 @ ./~/hapi/lib/index.js @ ./src/server.ts ERROR in ./~/hapi/lib/server.js Module not found: Error: Can't resolve 'catbox-memory' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib' @ ./~/hapi/lib/server.js 6:21-45 @ ./~/hapi/lib/index.js @ ./src/server.ts
你没有安装hapi
。 @types/hapi
只是TypeScript用于库的types定义,而不是实际的库本身。 所以你还需要添加hapi
:
npm install --save hapi
一旦你安装了它,模块可以被find,虽然你会得到一个新的错误./server
无法在hapi/lib/index.js
parsing,这是因为你configurationresolve.extensions
只包含.ts
,但是在离开分机时,库使用Node自动parsing.js
。 所以你也需要在扩展中包含.js
。
extensions: ['.ts', '.js'],
在解决这个问题之后,你会面对另外一个问题,就是像fs
这样的Node内置模块无法parsing。 默认情况下,webpack是为Web构build的,所以Node内置模块不可用。 但是你可以通过设置webpackconfiguration中的目标选项来改变node
:
target: 'node'
编辑
您在使用其他node_modules
遇到问题,因为您只使用顶层node_modules
,而不是始终回node_modules
的常规模块parsing,因此node_modules
应如下所示:
modules: [ path.resolve('src'), 'node_modules' ]