First of all, I'm struggling to ask the right question. I feel like I've missed or mixed some concepts regarding TypeScript compiler, new ES2015 (ES6) module syntax and module loaders.
I'm trying to import npm installed jquery module using ES2015 module syntax. Typescript should transpile it to ES5.
I get an error when opening index.html.
system-polyfills.src.js:1276 Error: SyntaxError: Unexpected token <
Evaluating http://localhost:3000/jquery
Error loading http://localhost:3000/app/main.js
index.html
<html>
<head>
<title>Bare TypeScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/jquery/dist/jquery.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<div>Loading...</div>
</body>
</html>
- I'm not sure if
<script
is necessary.
src="node_modules/jquery/dist/jquery.js"></script> - How come that B import works ok when
console.log($)
is commented
out? jQuery import should work too? - Maybe mixing npm's commonjs modules with systemjs is the problem?
main.ts
import * as $ from 'jquery'
import B from './app.b'
console.log("Monkey");
let b = new B();
console.log($);
How to configure tsc to work with ES2015 module syntax?
TypeScript 1.8 is used.
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
package.json
"dependencies": {
"es6-shim": "^0.35.0",
"jquery": "^2.2.2",
"systemjs": "0.19.25"
},
typings.json
{
"ambientDependencies": {
"es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
"jquery": "registry:dt/jquery#1.10.0+20160316155526"
}
}
Best Answer
You are trying to load jQuery as a systemjs module, but it's AMD. Also, unless you have a default export on your
app.b
, typescript compiler will throw an error. Did you check if you are getting any compiler errors?This Github has some insight on loading jQuery using ES6 import syntax.