Webpack 无法解析 TypeScript 模块 [英] Webpack cant resolve TypeScript modules

查看:73
本文介绍了Webpack 无法解析 TypeScript 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个中继小型 webpack 和 typescript 演示来玩.如果我使用 webpack.config.js 运行 webpack,我会收到此错误:

I build a relay small webpack and typescript demo to play with. If i run webpack with the webpack.config.js i get this error:

ERROR in ./js/app.ts
Module not found: Error: Can't resolve './MyModule' in '/Users/timo/Documents/Dev/Web/02_Tests/webpack_test/js'
 @ ./js/app.ts 3:17-38

我不知道可能是什么问题.模块导出应该是正确的.

I have no clue what the problem could be. The module export should be correct.

文件夹结构

webpack.config.js

webpack.config.js

const path = require('path');

module.exports = {
    entry: './js/app.ts',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {test: /.ts$/, use: 'ts-loader'}
        ]
    }
};

tsconfig.json

tsconfig.json

{
  "compilerOptions": {
        "target": "es5",
        "suppressImplicitAnyIndexErrors": true,
        "strictNullChecks": false,
        "lib": [
            "es5", "es2015.core", "dom"
        ],
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "dist"
    },
    "include": [
        "js/**/*"
    ]
}

src/app.js

import { MyModule } from './MyModule';

let mym = new MyModule();
console.log('Demo');

mym.createTool();
console.log(mym.demoTool(3,4));

src/MyModule.ts

src/MyModule.ts

export class MyModule {
   createTool() {
    console.log("Test 123");
  }

   demoTool(x:number ,y:number) {
    return x+y;
  }
};

src/index.html

src/index.html

<html>
    <head>
        <title>Demo</title>
        <base href="/">
    </head>
    <body>
        
        <script src="dist/bundle.js"></script>
    </body>
</html>

推荐答案

Webpack 默认不查找 .ts 文件.你可以配置 resolve.extensions 来查找.ts.也不要忘记添加默认值,否则大多数模块都会中断,因为它们依赖于自动使用 .js 扩展名的事实.

Webpack does not look for .ts files by default. You can configure resolve.extensions to look for .ts. Don't forget to add the default values as well, otherwise most modules will break because they rely on the fact that the .js extension is automatically used.

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

这篇关于Webpack 无法解析 TypeScript 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆