5
votes

The setting

I am trying to load existing AMD modules with TypeScript.

To demonstrate my problem, here is an app.ts file that loads an AMD module named my_amd_module.js:

// app.ts

import * as amd_func from './my_amd_module';

function main(): void {
  console.log(amd_func());
}

main();

The following TypeScript configuration is used:

// tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "allowJs": true,
    "outDir": "build",
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "build"
  ]
}

And I am using Webpack to bundle the app.ts file in a package named app-bundle.js that can be run by a browser:

// webpack.config.js

'use strict';

const webpack = require('webpack');
const path = require('path');

module.exports = {
  context: path.resolve(__dirname, 'src'),
  entry: './app.ts',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'app-bundle.js'
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.ts', '.js']
  },
  module: {
    loaders: [
      {test: /\.ts$/, loader: 'ts-loader'}
    ]
  }
};

The working version

When the my_amd_module.js looks as following, everything is working fine. Notice that I am referencing 'module' as a dependency and bind the function foo to it’s exports property which is one possible flavor of using AMD.

// my_amd_module.js

define(['module'], function(module) {
  function foo () {
    return 'Hello from AMD!';
  }

  module.exports = foo;
});

The not working version

But when I am using the alternative syntax of defining an AMD module with a return value instead of assigning to exports

// my_amd_module.js

define(function() {
  function foo () {
    return 'Hello from AMD!';
  }

  return foo;
});

then the TypeScript compiler complains with the following message:

ERROR in ./app.ts
(1,27): error TS2306: File '/[...]/src/my_amd_module.js' is not a module.

But the app-bundle.js file is still generated and everything works in the browser.

The alternative syntax I am using in this case is, for example, described by RequireJS or in the AMD specification itself.

My question

Are AMD modules that define their exported value with a return value instead of assigning to exports not supported by TypeScript? Is this the reason why the compiler is complaining? And why is everything compiled, despite this complaint?

1

1 Answers

0
votes

Are AMD modules that define their exported value with a return value instead of assigning to exports not supported by TypeScript

Yes. Apparently it is not detected as an external module and inferred to be global and hence not allowed to be required. Please raise an issue here : https://github.com/Microsoft/TypeScript/issues