2017-07-31 62 views
0

我使用相对路径在TypeScript中导入了一个模块。TypeScript相对路径导入在Webpack中不起作用

// index.ts 
import {Widget} from './components/Widget'; 

的WebPack给了我以下错误:

ERROR in ./src/index.ts 
Module not found: Error: Can't resolve './components/Widget' in 
C:\project\src' @ ./src/index.ts 4:19-51 

我的WebPack配置文件是非常基本的,在规则的TS-装载机和指向index.ts作为入口文件。

我在做什么错在这里?


其他信息:

项目文件夹结构:

c:\project 
├─ src 
│ ├─ index.ts 
│ └─ components 
│  └─ Widget.ts 
├─ webpack.config.js 
└─ tsconfig.json 

的WebPack配置:

const path = require('path'); 

const config = { 
    entry: './src/index.ts', 
    output: { 
    path: path.resolve(__dirname, 'dist'), 
    filename: 'bundle.js' 
    }, 
    module: { 
    rules: [ 
     { test: /\.tsx?$/, use: 'ts-loader' } 
    ] 
    } 
}; 

module.exports = config; 

tsconfig.json

{ 
    "compilerOptions": { 
     "outDir": "dist", 
     "module": "commonjs", 
     "target": "es6" 
    }, 
    "include": [ "src/**/*" ], 
    "exclude": [ 
     "node_modules" 
    ] 
} 

版本:

webpack 3.1.0 
typescript 2.4.1 
ts-loader 2.2.2 
+0

您的'webpack.config.js'文件位于何处? – Saravana

+0

@Saravana我在答案中将信息添加到了项目结构中。 – fafaro

+1

你可以发布你的'tsconfig.json'吗?只要你在'tsconfig.json'中没有任何路径映射,这应该工作。 – Saravana

回答

0

添加resolve.extensions您webpack.config.js。

{ 
    resolve: { 
     extensions: ['.ts', '.js', '.json'] 
    } 
} 

中的WebPack默认模块的分辨率,当你在你的模块中(ref)写的扩展名的进口搜索只为.js.json文件。

所以,当你写:

import {Widget} from './components/Widget'; 

的WebPack只对这些文件的搜索默认为:

./components/Widget.js 
./components/Widget.json 

,从而最终给Module not found错误。