Как добавить скомпилированные веб-пакетом JS библиотеки в автозаполнение Монако - PullRequest
0 голосов
/ 22 апреля 2020

Как мне добавить javascript библиотеки, которые были упакованы в мой редактор monaco для автоматического заполнения? enter image description here

Я пытаюсь создать среду, в которой пользователи могут создавать сценарии определенных взаимодействий с моим сайтом, и я хочу предоставить «стандартную библиотеку», которая предоставляет API-доступ к сайту.

Я пытался использовать addExtraLib, но ожидается, что файлы d.ts не генерируются из библиотек JS. Я попытался создать их, но безуспешно. Как мне этого добиться? addExtraLib даже правильная вещь в этой ситуации?

Вот индекс моего редактора в Монако. js:

import * as monaco from "monaco-editor/esm/vs/editor/editor.api";   //Imports Monaco
import Mixy from "../mixy/mixy";                                    //Imports my Mixy Library. Webpack externals rule overrides this.

(async function () {
    // create div to avoid needing a HtmlWebpackPlugin template
    const div = document.createElement('div');
    div.id = 'root';
    div.style = 'width:800px; height:600px; border:1px solid #ccc;';
    document.body.appendChild(div);


    // validation settings
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: true,
        noSyntaxValidation: false
    });

    // compiler options
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
        target: monaco.languages.typescript.ScriptTarget.ES6,
        allowNonTsExtensions: true,
        allowJs: true,
    });


    //This does work, but having to redefine my library in here would be less than ideal
    const fact = `declare namespace custom { export function onMyEvent(event: customClass): void;
        export class customClass { 
            customProperty: string;
        }`;
    monaco.languages.typescript.javascriptDefaults.addExtraLib(fact, 'myCustomNamespace');

    //This doesn't work. No errors occur, but there is also no auto-complete for 'Mixy' or 'mixy' or '(new Mixy())'
    let response = await fetch('/dist/mixy.js');
    let body = await response.text();
    monaco.languages.typescript.javascriptDefaults.addExtraLib(body, 'mixyjs');


    let editor = monaco.editor.create(
        document.getElementById('root'),
        {
            value: 'var a = 1;',
            language: 'javascript',
            theme: 'vs-dark'
        }
    );
})();

Вот моя библиотека Mixy, которую я пытаюсь добавить:

import './mixy.css';        //Page styling
import './oAuthPopup.js';   //Library that adds "document.createModal"

import { ShortCodeExpireError, ShortCodeAccessDeniedError, OAuthClient }  from '@mixer/shortcode-oauth';

export class Mixy {

    /** OAuthClient used by the shortcode. Using experimental privates from babel */
    #mixerOAuthClient;
    #shortCodeModal;

    /** Sets teh defaults configuration from the outside */
    configureOAuth(options) {
        this.#mixerOAuthClient = new OAuthClient(options);
    }

    /** Attempts to perform a login */
    async mixerLogin() {

        let modal = this.#getShortCodeModal();
        modal.show();

        // .. Does Token Stuff ..

        //Close the modal windows
        modal.hide(); 
        modal.closeWindow();

        if (tokens) {

            //Store the tokens
            let response = await fetch('/auth', {
                method: 'POST',
                credentials: 'include',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify(tokens),
            });

            if (response.ok) return true;
            return response.statusText;
        }

        return false;
    }

    #getShortCodeModal() {
        if (this.#shortCodeModal != null) return this.#shortCodeModal;

        // .. Creates popup modals ..

        return this.#shortCodeModal;
    }
}

Вот мой webpack.config. js


const MixyConfiguration = {
    entry: './src/mixy/mixy.js',
    output: {
        filename: 'mixy.js',
        chunkFilename: 'vendor.[name].js',
        path: path.resolve(__dirname, 'public/dist'),
        publicPath: '/dist/',
        library: 'mixy',
    },
    module: {
        rules: [
          {
            test: /\.m?js$/,
            use:  {
              loader: 'babel-loader', 
              options: {
                plugins: [
                  "@babel/plugin-proposal-class-properties",
                  "@babel/plugin-proposal-private-methods"
                ]
              },
            }
          },
          {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/,
          },      
          {
            test: /\.css$/i,
            use: [
                'style-loader',
                'css-loader',
                'sass-loader',
            ],
          },
          {
            test: /\.s[ac]ss$/i,
            use: [
              MiniCssExtractPlugin.loader,
              { loader: 'css-loader' },
              { loader: 'sass-loader', options: { sourceMap: true } },
            ]
          }
      ]
    },
    plugins: [ new MiniCssExtractPlugin({ filename: 'mixy.css' }), ],
    devtool: 'source-map',
}

const MonacoConfiguration = {
    entry: './src/monaco/index.js',
  output: {
    chunkFilename: '[name].bundle.js',
    path: path.resolve(__dirname, 'public/dist'),
    publicPath: '/dist/',
  },
    module: {
        rules: [{
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        }, {
            test: /\.ttf$/,
            use: ['file-loader']
        }]
  },
  plugins: [
        new MonacoWebpackPlugin({
            languages: ["typescript", "javascript", "css", "html"],
        })
  ],
  externals: {
    '../mixy/mixy': 'mixy'
  }
}

module.exports = [ MixyConfiguration, MonacoConfiguration ];

Вот весь проект: lachee / mixy (филиал Монако)

...