TypeScript Playground does not seem to balk at this import:
import * as _ from "underscore";
until you try to use it, like:
const equalResult = _.isEqual('ABC', '123');
Then, it generates the error:
[ERR]: Executed JavaScript Failed:
[ERR]: Cannot use import statement outside a module
The playground seems to understand the library because it gives JSDoc, so I'm thinking that this can work, but how?
To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .
TypeScript Playground isn't a fully fledged sandbox solution. It's merely meant as a simple type explorer that doesn't need dependencies.
For your use case I would recommend using CodeSandbox instead. It comes with a whole bunch of TypeScript templates to choose from when creating a sandbox. TypeScript Playground also has an export menu where you can open your code in CodeSandbox directly.
The UI is based off of VS Code, so if you're used to that you will feel just at home.
If by "importing" you mean using import
to include an npm package that can be accessed at runtime, that is not a feature of the TypeScript Playground, unfortunately; it's intended for testing features of the language and the compiler.
You'll need to use a sandbox environment if you want to include npm packages, bundlers, etc.; checkout CodeSandbox, as others have suggested.
About your particular error:
[ERR]: Executed JavaScript Failed: [ERR]: Cannot use import statement outside a module
This is due to your current configuration, not the lack of package support by TypeScript Playground. By default, your .js output probably looks something like this:
import * as _ from "underscore";
const equalResult = _.isEqual('ABC', '123');
This is because the default module
setting in the Playground is set to ESNext
.
If we change this to CommonJS
for example, we get:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ?
// A bunch more lines .....
const _ = __importStar(require("underscore"));
const equalResult = _.isEqual('ABC', '123');
Now we get another error that tells us explicitly that our package is unavailable:
[ERR]: "Executed JavaScript Failed:"
[ERR]: Check dependency list! Synchronous require cannot resolve module 'underscore'.
This is the first mention of this module!
While the playground is smart enough to auto-import the types for import
statements, it doesn't support external modules outside of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With