LoginSignup
6

More than 3 years have passed since last update.

posted at

updated at

TypeScript + webpackでModule not foundでハマった

webpackでコンパイルする際にハマったのでメモ。

ファイル構成

node_modules
src
  ├─dist
  ├─app.ts
  └─functions.ts
package.json
package-lock.json
tsconfig.json
webpack.config.js
src/app.ts
import * as functions from './functions';

functions.a();
functions.b();
src/functions.ts
export function a() {
    console.log('a');
}

export function b() {
    console.log('b');
}
webpack.config.js
const path = require('path');

module.exports = {
    entry: {
        app: './src/app.ts',
    },
    output: {
        path: path.resolve(__dirname, 'src/dist'),
        filename: '[name].js'
    },
    resolve: {
        modules: [path.resolve(__dirname, 'src'), 'node_modules']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }
        ]
    }
}
package.json
{
    "scripts": {
        "dev": "webpack --mode development"
    }
}

コンパイル

npm run dev

結果

> test-ts@1.0.0 dev C:\testts
> webpack --mode development

Hash: 99f990c29902dfc250ea
Version: webpack 4.41.1
Time: 1510ms
Built at: 2019-10-14 6:02:12 PM
 Asset      Size  Chunks             Chunk Names
app.js  4.07 KiB     app  [emitted]  app
Entrypoint app = app.js
[./src/app.ts] 154 bytes {app} [built]

ERROR in ./src/app.ts
Module not found: Error: Can't resolve './functions' in 'C:\testts\src'
 @ ./src/app.ts 3:18-40
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! test-ts@1.0.0 dev: `webpack --mode development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the test-ts@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2019-10-14T09_02_12_974Z-debug.log

修正

webpack.config.js
module.exports = {
    resolve: {
        extensions: ['.ts'],
        modules: [path.resolve(__dirname, 'src'), 'node_modules']
    }
}

resolve.extensionsが必要でした。
考えてみればimport * as functions from './functions';では拡張子がないので指定しないといけないですね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
6