2
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-10-14

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';では拡張子がないので指定しないといけないですね。

2
7
0

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
  3. You can use dark theme
What you can do with signing up
2
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?