How to import library with TypeScript Playground
Matthew Harrington
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 moduleThe playground seems to understand the library because it gives JSDoc, so I'm thinking that this can work, but how?
33 Answers
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.
2If 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.
I came here trying to solve that same problem, and then continued digging, and this was the best solution I came up with:
If you go to , you can select "Typescript" as your language and "underscore.js" as your library and it should create a similar environment to the playground. The language and library can be selected by clicking the language type above the JS text box in the JFiddle website.
Doesn't answer your original question, but may be a viable work around for someone.