简体   繁体   中英

Webpack and TypeScript: module resolution error

I have a project with TypeScript and Webpack. I want to import files without extension.

This is my tree:

.
├── .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

When in App.ts I do:

import usersRouter from './routes/user';

Instead of

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

I get:

[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...

This is my 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/
            }
        ]
    }
};

This my tsconfig.js :

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

Here 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,
    };
};

This my 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"
    }
}

I know this is a common error, but I'm not sure how to fix it.

Any idea will be welcome!

You have to tell webpack to resolve .ts extensions. For example add:

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

to your webpack.config.js file.

For more information see the webpack resolve documentation . And in particular the resolve extensions chapter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM