Webpack和TypeScript:模块解析错误

时间:2019-09-13 11:55:58

标签: javascript node.js typescript webpack

我有一个带有TypeScript和Webpack的项目。我想导入不带扩展名的文件。

这是我的树

.
├── .eslintrc.js
├── .gitignore
├── README.md
├── babel.config.js
├── config.test.json
├── dist
│   └── api.js
├── package.json
├── src
│   └── api
│       ├── App.ts
│       └── routes
│           └── user.ts
├── tsconfig.json
└── webpack.common.js

App.ts时,我会这样做:

import usersRouter from './routes/user';

代替

import usersRouter from './routes/user.ts';

我得到:

[1] /Users/me/projects/project/dist/api.js:100
[1] __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module './routes/user'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
[1]                                                                                                                                                  ^
[1]
[1] Error: Cannot find module './routes/user'
[1]     at webpackMissingModule (/Users/me/projects/project/dist/api.js:100:65)
[1]     at Object../src/api/App.ts (/Users/me/projects/project/dist/api.js:100:156)
[1]     at __webpack_require__ (/Users/me/projects/project/dist/api.js:21:30)
[1]     at Object.0 (/Users/me/projects/project/dist/api.js:176:18)
[1]     at __webpack_require__ (/Users/me/projects/project/dist/api.js:21:30)
[1]     at /Users/me/projects/project/dist/api.js:85:18
[1]     at Object.<anonymous> (/Users/me/projects/project/dist/api.js:88:10)
[1]     at Module._compile (internal/modules/cjs/loader.js:721:30)
[1]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
[1]     at Module.load (internal/modules/cjs/loader.js:620:32)
[1] [nodemon] app crashed - waiting for file changes before starting...

这是我的webpack.common.js

const nodeExternals = require('webpack-node-externals'); // Remove node_modules when creating the bundle

module.exports = {
    entry: ['@babel/polyfill', './src/api/App.ts'],
    output: {
        filename: 'api.js',
        path: __dirname + '/dist',
        libraryTarget: 'commonjs2'
    },
    target: 'node',
    node: {
        console: false,
        global: false,
        process: false,
        Buffer: false,
        __filename: false,
        __dirname: false
    },
    externals: [nodeExternals()],
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    }
};

这是我的tsconfig.js

{
    "compilerOptions": {
        "outDir": "./dist/",
        "target": "es5",
        "allowJs": true,
        "sourceMap": true,
        "allowSyntheticDefaultImports": true
    },
    "include": ["src"],
    "exclude": ["node_modules"]
}

这里babel.config.js

module.exports = function(api) {
    api.cache(true);

    const presets = ['@babel/preset-env'];
    const plugins = [
        '@babel/plugin-transform-arrow-functions',
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-syntax-dynamic-import',
        '@babel/plugin-proposal-object-rest-spread',
    ];

    return {
        presets,
        plugins,
    };
};

这是我的Package.json

{
    "name": "@me/project",
    "version": "0.0.1",
    "description": "An API",
    "main": "dist/api.js",
    "scripts": {
        "start": "concurrently \"npm run buildDev\" \"npm run startDev\"",
        "buildDev": "webpack --watch --config webpack.dev.js",
        "startDev": "nodemon --inspect ./dist/api.js"
    },
    "devDependencies": {
        "@babel/cli": "^7.2.3",
        "@babel/core": "^7.2.2",
        "@babel/plugin-proposal-class-properties": "^7.3.0",
        "@babel/plugin-proposal-object-rest-spread": "^7.3.2",
        "@babel/plugin-syntax-dynamic-import": "^7.2.0",
        "@babel/plugin-transform-arrow-functions": "^7.2.0",
        "@babel/plugin-transform-strict-mode": "^7.2.0",
        "@babel/preset-env": "^7.3.1",
        "autoprefixer": "^8.4.1",
        "babel-core": "^7.0.0-bridge.0",
        "babel-eslint": "^10.0.1",
        "babel-jest": "^24.1.0",
        "babel-loader": "^8.0.5",
        "babel-minify-webpack-plugin": "^0.3.1",
        "eslint": "^4.19.1",
        "eslint-formatter-pretty": "^1.3.0",
        "eslint-loader": "^2.1.2",
        "eslint-plugin-import": "^2.16.0",
        "file-loader": "^1.1.11",
        "lint-staged": ">=8",
        "ts-loader": "^5.3.3",
        "typescript": "^3.6.3",
        "webpack": "^4.40.1",
        "webpack-bundle-analyzer": "^2.13.1",
        "webpack-cli": "^3.2.3",
        "webpack-dev-server": "^3.1.14",
        "webpack-node-externals": "^1.7.2"
    },
    "dependencies": {
        "@babel/polyfill": "^7.2.5",
        "@types/body-parser": "^1.17.0",
        "@types/cookie-parser": "^1.4.2",
        "@types/cors": "^2.8.6",
        "@types/express": "^4.17.1",
        "@types/morgan": "^1.7.37",
        "@types/node": "^12.7.5",
        "babel-polyfill": "^6.26.0",
        "concurrently": "^3.6.1",
        "cookie-parser": "~1.4.3",
        "cors": "^2.8.5",
        "express": "^4.16.3",
        "express-useragent": "^1.0.12",
        "nodemon": "^1.18.9",
        "npm": "^6.7.0",
        "passport": "^0.4.0",
        "passport-jwt": "^4.0.0",
        "passport-local": "^1.0.0",
        "prettier-eslint": "^8.8.1",
        "ts-node": "^8.0.2",
        "webpack-merge": "^4.2.1"
    }
}

我知道这是一个常见错误,但是我不确定如何解决。

任何想法都会受到欢迎!

1 个答案:

答案 0 :(得分:1)

您必须告诉webpack解析.ts扩展名。例如添加:

resolve: {
    // Add .ts and .tsx as a resolvable extension.
    extensions: [".ts", ".tsx", ".js"]
}

到您的webpack.config.js文件。

有关更多信息,请参见webpack resolve documentation。尤其是resolve extensions这一章。