导入不使用TypeScript导出的AMD模块

时间:2016-05-04 18:37:32

标签: javascript typescript amd

设置

我正在尝试使用TypeScript加载现有的AMD模块。

为了演示我的问题,这里有一个app.ts文件,用于加载名为my_amd_module.js的AMD模块:

// app.ts

import * as amd_func from './my_amd_module';

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

main();

使用以下TypeScript配置:

// tsconfig.json

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

我正在使用Webpack将app.ts文件捆绑在一个名为app-bundle.js的包中,该包可以由浏览器运行:

// 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'}
    ]
  }
};

工作版

my_amd_module.js看起来如下,一切正常。请注意,我将'module'作为依赖项引用,并将函数foo绑定到它的exports属性,这是使用AMD的一种可能的风格。

// my_amd_module.js

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

  module.exports = foo;
});

无效版本

但是当我使用替代语法来定义带有返回值的AMD模块而不是分配给exports

// my_amd_module.js

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

  return foo;
});

然后TypeScript编译器抱怨以下消息:

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

app-bundle.js文件仍然生成,一切都在浏览器中运行。

我在这种情况下使用的替代语法是,例如described by RequireJSin the AMD specification itself

我的问题

AMD模块是否使用return值定义其导出值而不是分配给TypeScript不支持的exports?这是编译器抱怨的原因吗?尽管有这样的抱怨,为什么一切都会被编译?

1 个答案:

答案 0 :(得分:0)

  

AMD模块是否使用返回值定义其导出值,而不是分配给TypeScript不支持的导出

是。显然,它未被检测为外部模块,并推断为global,因此不允许require d。请在此处提出问题:https://github.com/Microsoft/TypeScript/issues

相关问题