Why am I getting "Unexpected token import" on one webpack project but not the other?
I had a similar issue where I was using async\await and Promises (both ES6 constructs) using the import keyword in the ts source files to import other ts modules.
I could transpile with TypeScript using the default js target version (ES5) which produces transpile errors complaining about the async\await and Promise keywords but since I'm actually running Node 6.4.0. everything actually works at runtime.
In the case described above, the 'Import' keyword was translated from ts to js as:
var BasePage_1 = require('./BasePage');
So, I'm getting tsc transpile errors but Node works fine at runtime with the above 'Import' translation.
If I use the -t switch to tell tsc to transpile to ES6 then the transpile is clean with no errors but then Node fails because it says it doesn't understand the 'Import' keyword in the emitted js file.
Now, tsc emits the following translation for 'Import':
import { BasePage } from './BasePage';
So, the above translation really isn't a translation at all and Node chokes on the js file with the 'Import' keyword at runtime.
Summary:
I solved this conundrum using this command line to tell tsc to use ES6 libraries but to emit the proper module import syntax:
myTypeScriptSourceFile.ts -t ES6 -m commonjs
Now I get a clean transpile and no runtime errors from Node. Because now 'Import'
is being properly translated using the 'require'
reserved word.
More details here: https://www.typescriptlang.org/docs/handbook/compiler-options.html https://www.typescriptlang.org/docs/handbook/module-resolution.html
addendum to the accepted answer for the busy programmer, the command line option can also be made inside tsconfig.json
file:
{
"compilerOptions": {
// ...other options
"module": "commonjs", // add this
"target": "es6", // and this
}