我想为我的js库创建d.ts文件。但是,当我想将此模块导入ts文件时,webpack会引发错误:
ERROR in ./index.ts
Module not found: Error: Can't resolve 'TestModule'
我的文件夹结构如下:
- root
--definitions
-- TestModule
--index.d.ts
--src
--index.ts
--index.html
--tsconfig.json
--webpack.config.js
tsconfig
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"outDir": "dist",
"lib": ["es2017", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"removeComments": true,
"typeRoots": [
"./node_modules/@types",
"./definitions"
]
},
"exclude": ["node_modules", "dist"]
}
webpack.config
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = nodeEnv === 'production';
const plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
}),
new HtmlWebpackPlugin({
title: 'Typescript Webpack Starter',
template: '!!ejs-loader!src/index.html'
}),
new webpack.LoaderOptionsPlugin({
options: {
tslint: {
emitErrors: true,
failOnHint: true
}
}
})
];
var config = {
devtool: isProd ? 'hidden-source-map' : 'source-map',
context: path.resolve('./src'),
entry: {
app: './index.ts'
},
output: {
path: path.resolve('./dist'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
enforce: 'pre',
test: /\.tsx?$/,
exclude: [/\/node_modules\//],
use: ['awesome-typescript-loader', 'source-map-loader']
},
!isProd
? {
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
exclude: [/\/node_modules\//],
query: {
esModules: true
}
}
: null,
{ test: /\.html$/, loader: 'html-loader' },
{ test: /\.css$/, loaders: ['style-loader', 'css-loader'] }
].filter(Boolean)
},
resolve: {
extensions: ['.ts', '.js']
},
plugins: plugins,
devServer: {
contentBase: path.join(__dirname, 'dist/'),
compress: true,
port: 3000,
hot: true
}
};
module.exports = config;
index.ts
import TestModule from 'TestModule';
console.log(TestModule.sum(1, 2));
和定义文件-index.d.ts
interface ITestModule {
sum(number1: number, number2: number):number;
}
declare const TestModule: ITestModule;
declare module "TestModule" {
export default TestModule;
}
导入TestModule时可以看到类型,但是我不知道为什么webpack会抛出错误。
@编辑
当我删除导入statemnet时,它似乎可以正常工作,但没有收到任何错误。但是,当我在浏览器中打开应用程序时,我可以看到
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for '...d.ts file'