'Get logs "Cannot use import statement outside a module " when run code in TypeScript Playground
I had added Custom npm Modules lodash in the TypeScript Playground plugins tab.
The TS config looks fine as well. When I run below code:
import _, { Dictionary } from 'lodash';
export function omitFalsyFields<T extends Dictionary<any>>(params: T) {
return _.omitBy(params, (k) => !k);
}
interface CreateUserParams {
name?: string;
email: string;
}
const params = omitFalsyFields({ name: '', email: '[email protected]' })
console.log(params)
Got logs:
[ERR]: "Executed JavaScript Failed:"
[ERR]: Cannot use import statement outside a module
When I check the console of my browser, It seems these two errors are thrown by react_devtools_backend.js. My code doesn't include any React code.
What's going on? I expect the console.log(params) to execute correctly and print the log.
Solution 1:[1]
I got imports to work in ts playground with this hacky solution below:
const AsyncFunction = (async () => {}).constructor as FunctionConstructor;
const _import = (mod: string) => {
return (new AsyncFunction('', `return import('https://cdn.skypack.dev/${mod}')`))()
}
import type { Dictionary } from 'lodash';
(async () => {
const _ = await _import('lodash') as typeof import('lodash');
function omitFalsyFields<T extends Dictionary<any>>(params: T) {
return _.omitBy(params, (k) => !k);
}
interface CreateUserParams {
name?: string;
email: string;
}
const params = omitFalsyFields({ name: '', email: '[email protected]' })
console.log(params)
})()
You do need to change your module setting to commonjs for this to work, maybe a better solution is to write a playground plugin to transform normal imports to this format or something similar.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zou Jeff |



