Import AMD modules that do not use export with TypeScript

Customization

I am trying to load existing AMD modules using TypeScript.

To demonstrate my problem, here is the app.ts file that loads the 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 use Webpack to link the app.ts file in a package called app-bundle.js that can be launched by the 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'} ] } }; 

Working version

When my_amd_module.js looks like this, everything works fine. Note that I refer to 'module' as a dependency and bind the foo function to the exports property, which is one of the possible uses for AMD.

 // my_amd_module.js define(['module'], function(module) { function foo () { return 'Hello from AMD!'; } module.exports = foo; }); 

Broken version

But when I use alternative syntax to define an AMD module with a return value instead of assigning exports

 // my_amd_module.js define(function() { function foo () { return 'Hello from AMD!'; } return foo; }); 

then the TypeScript compiler complains about 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 is still generated and everything works in the browser.

An alternative syntax that I use 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 return value instead of assigning exports not supported by TypeScript? Is this the reason the compiler complains? And why is everything compiled despite this complaint?

+5
source share
1 answer

Are AMD modules that define an exported value with a return value instead of an export destination not supported by TypeScript

Yes. Apparently, it is not detected as an external module and cannot be global and, therefore, require d is not allowed. Please raise a question here: https://github.com/Microsoft/TypeScript/issues

0
source

All Articles