M
M
ML2017-12-04 14:33:55
Node.js
ML, 2017-12-04 14:33:55

TypeScript alias setup?

src --
       -- modules
           -- module1
           -- module2
       -- app
            -- main.ts
package.json
tsconfig.json
webpack.config.js

webpack.config.js:
'use strict';

const webpack           = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path              = require( 'path' );

module.exports = {
  entry: {
    common: './src/app/common.ts',
    main: './src/app/main.ts'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    alias: {
      module1: path.resolve(__dirname, 'src/modules/module1'),
      module2: path.resolve(__dirname, 'src/modules/module2')
    }
  },
  module: {
    loaders: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ],
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [ 'css-loader', 'sass-loader' ]
        })
      }
    ]
  },
  plugins: [
  ]
}

Why alias is pulled correctly:
that is, this works in main.ts:
import {AllSiteData} from 'module1'
console.log(AllSiteData);

in the browser console everything is correct:
{
logo: 'p.png',
title: 'Site name'
}

And in the nodejs console, this is issued:
error TS2307: Cannot find module 'module1'.
However, if I correct on in main.ts, on: Then everything works. How to properly set up, or rather complete the alias, so that typescript can also see them. Here is my tsconfig.js:
import {AllSiteData} from '../modules/module1';
{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "experimentalDecorators": true,
    "jsx": "react",
    "allowJs": true,
    "alwaysStrict": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "paths": {
      "module1": ["src/modules/module1"],
      "module2": ["src/modules/module2"]
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2017-12-04
@staffID

If you try to compile the code you provided with the tsc command at the root of the project, it immediately shows an error:

tsconfig.json(15,5): error TS5060: Option 'paths' cannot be used without specifying '--baseUrl' option.

Well, actually, when added "baseUrl": "./"to tsconfig, everything works :)
PS Thank you, now I know that tsc supports aliases :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question