Skip to content

Invalid code generation with --module=amd and --resolveJsonModule=true #25517

@LeviticusMB

Description

@LeviticusMB

TypeScript Version: Version 3.0.0-dev.20180707

Search Terms: amd json

Code

  1. Init workspace
#!/bin/bash

npm init --yes
npm add requirejs typescript@next
mkdir src

cat > src/main.ts <<EOF
import data from './data.json'
console.log('data.json:', data)
EOF

cat > src/data.json <<EOF
[ "a", "json", "object" ]
EOF

cat > tsconfig-commonjs.json <<EOF
{
  "compilerOptions": {
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "outDir": "./build",
    "module": "commonjs",
    "moduleResolution": "node"
  },
  "include": ["src"]
}
EOF

cat > tsconfig-amd.json <<EOF
{
  "compilerOptions": {
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "outFile": "./build/bundle.js",
    "module": "amd",
    "moduleResolution": "node"
  },
  "include": ["src"]
}
EOF

npx tsc --version
npx tsc -p tsconfig-commonjs.json
npx tsc -p tsconfig-amd.json

cat > run-commonjs.js <<EOF
#!/usr/bin/env node
require('./build/main')
console.log('Done');
EOF

(echo '#!/usr/bin/env node'; cat node_modules/requirejs/require.js build/bundle.js -) > run-amd.js << EOF
requirejs(['main'], function (main) {
  console.log('Done');
})
EOF

chmod +x run-commonjs.js run-amd.js

#rm -rf build src node_modules package*.json run*.js tsconfig*.json
  1. Run ./run-commonjs.js
  2. Run ./run-amd.js

Expected behavior:

Both scripts output

data.json: [ 'a', 'json', 'object' ]
Done

Actual behavior:

Only the commonjs version works. The AMD version can be fixed by applying this patch:

--- run-amd.js	2018-07-09 18:44:56.000000000 +0200
+++ run-amd-fixed.js	2018-07-09 18:50:19.000000000 +0200
@@ -2147,7 +2147,7 @@
 var __importDefault = (this && this.__importDefault) || function (mod) {
     return (mod && mod.__esModule) ? mod : { "default": mod };
 };
-["a", "json", "object"]
+define("data", [], ["a", "json", "object"])
 define("main", ["require", "exports", "data"], function (require, exports, data_json_1) {
     "use strict";
     exports.__esModule = true;

As you can see, the compiler outputs the json data as-is, without wrapping it with the required module definition code. Note that --module=system generates the same plain json-object in the bundle.

Playground Link:

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions