microsoft / monaco-editor

A browser based code editor
https://microsoft.github.io/monaco-editor/
MIT License
40.63k stars 3.61k forks source link

Importing JSON in Typescript file results in error #2348

Open StefanRetief opened 3 years ago

StefanRetief commented 3 years ago

I'm attempting to import a JSON editor model in withing a typescript editor model. I've been able to successfully do this within vscode but haven't had any luck with monco-editor as it shows a validation error "Cannot find module {...} or its corresponding type declarations". I was able to import a typescript model in using the same method I am using for the json model and i've adjusted the typescript/javascript compiler options to match that of my vscode version, which should allow json modules to be resolved.

monaco-editor version: 0.22.3 Browser: Firefox OS: Windows Playground code that reproduces the issue:


monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES6,
    resolveJsonModule: true,
    esModuleInterop: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs
});

monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES6,
    resolveJsonModule: true,
    esModuleInterop: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs
});

// extra libraries
var jsonlibSource = [
    '{',
    '   "name": "myName"',
    '}',
].join('\n');
var jsonlibUri =  monaco.Uri.file('./facts.json');
monaco.editor.createModel(jsonlibSource, 'json', jsonlibUri);

// extra libraries
var tslibSource = [
    'export const tstest = "myname";'
].join('\n');
var tslibUri =  monaco.Uri.file('./facts.ts');
monaco.editor.createModel(tslibSource, 'typescript', tslibUri);

var jsCode = [
    'import test from "./facts.json";',
    'import { tstest } from "./facts";',
    'console.log(test)',
    'console.log(tstest)'
].join('\n');

var file =  monaco.Uri.file('./test.ts');
const fileModel = monaco.editor.createModel(jsCode, 'typescript', file);

const editor = monaco.editor.create(document.getElementById('container'));

editor.setModel(fileModel)
abcirta commented 2 years ago

Same here, using import fails... using require works but no type is inferred

akcyp commented 1 year ago

Any update on this? @StefanRetief @arslan-bz did you found the solution?

StefanRetief commented 1 year ago

@akcyp unfortunately not. I converted my json files to ts files before loading them into the editor or used require.