0
votes

Problem

When I run a nodemon with npm run start, I get Error: Cannot find module 'Test', and When I build files with npm run build and run ./dist/index.js, I get the same error.

As you can see, a require path on ./dist/index.js is not recognized properly.

I don't know which configuration have to be changed, so I questioned.

If you know about that, Please reply back to me with your asnwer. Thanks :)

Source Code

./src/index.ts

import Test from 'Test';

const test = new Test();

./src/Test/index.ts

export default class Test {
    constructor () {
        console.log('Test');
    }
}

./dist/index.js

"use strict";

var _Test = _interopRequireDefault(require("Test"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var test = new _Test.default();

./package.json

{
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "babel ./src --extensions .ts,.js --out-dir ./dist",
    "start": "nodemon ./src --exec babel-node --extensions .ts,.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.0.0-beta.47",
    "@babel/core": "^7.0.0-beta.47",
    "@babel/node": "^7.0.0-beta.47",
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.47",
    "@babel/plugin-proposal-object-rest-spread": "^7.0.0-beta.47",
    "@babel/polyfill": "^7.0.0-beta.47",
    "@babel/preset-env": "^7.0.0-beta.47",
    "@babel/preset-typescript": "^7.0.0-beta.47",
    "cross-env": "^5.1.5",
    "nodemon": "^1.17.4"
  }
}

./tsconfig.json

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "experimentalDecorators": true,
        "forceConsistentCasingInFileNames": true,
        "lib": ["ES2015", "ES2017", "DOM"],
        "noEmit": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "module": "esnext",
        "moduleResolution": "node",
        "paths": { "*":["node_modules/*", "src/*"] },
        "pretty": true,
        "strictNullChecks": true,
        "target": "es5",
        "typeRoots": ["./node_modules/@types"]
    }
}

./.babelrc

{
    presets: ['@babel/preset-env', '@babel/preset-typescript'],
    plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-object-rest-spread']
}
1
I've solved this problem using a module-alias pakage :Dleft click

1 Answers

2
votes

Try import Test from './Test'; in your ./src/index.ts. Because without relative path typescript looks for the global module Test. When you want to use local module you should use relative path to your module.