Webpack无法解析TypeScript模块

JavaScript Webpack

猴子Sam宝儿

2020-03-24

我构建了一个中继小型webpack和TypeScript演示来玩。如果我使用webpack.config.js运行webpack,则会出现此错误:

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

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

资料夹结构

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

{
  "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

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

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

src / index.html

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

第3651篇《Webpack无法解析TypeScript模块》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
宝儿 2020.03.24

我使用的是tsconfig而不是webpack,它还将子模块编译为捆绑包(index.js)。

对我来说,问题是我在tsc从外部引用子模块之前忘记编译子模块(即运行生成index.js)。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android