Using monaco-editor with typescript without webpack in an electron project - node.js

I'm trying to use monaco-editor in an electron typescript project. I installed it via
npm install -D monaco-editor.
I import it with import { editor } from "monaco-editor"; My IDE (WebStorm) doesn't complain about an unfound module, however after running the app I get the following error:
Uncaught Error: Cannot find module 'monaco-editor' from internal/modules/cjs/loader.js:801 in the console.
I have already tried
Downloading the package manualy
Reinstalling the module
Cloning the code from the official repository
I was able to run official samples, those however use pure javascript. I also do not use WebPack. I suppose that should not make a difference, however it is used in all getting started and installation guides.
What is the source of that error and how can I fix it?
P.S. You can find the full code on github if you need more context

I managed to make it work.
So for those who try:
tsconfig.json
Try to make the typescript compiler ignore the errors in the monaco library.
"compilerOptions": {
"checkJs": false,
"skipLibCheck": true,
},
rollup.config.js
Make the bundler accept importing css files, also adding the line inlineDynamicImports: true fix the compile. I am not sure what the impact is yet.
import rollupPluginCssOnly from 'rollup-plugin-css-only'
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
inlineDynamicImports: true
},
plugins: [
rollupPluginCssOnly({
output: 'public/build/extra.css'
}),
html page
I use svelte but this can be converted to plain html easily (using for example getDocumentById to get the element).
<script lang="ts">
import { onMount } from 'svelte'
import './extra.css'
import * as monaco from 'monaco-editor'
var containerElt: HtmlDivElement
onMount(() => {
monaco.editor.create(containerElt, {
value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join(
'\n',
),
language: 'javascript',
})
})
</script>
<style>
div {
width: 100%;
height: 100%;
}
</style>
<svelte:head />
<div bind:this={containerElt} />

Related

rollup.js: crypto.getRandomValues() not supported

I am working on an Obsidian plugin that requires bundling using rollup.js. This plugin needs to import inrupt solid libraries that, when imported, are causing the following error:
Error: crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported
at rng (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:16740:10)
at v4 (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:17186:53)
at new Session (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23526:88)
at Repro.<anonymous> (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23669:17)
at step (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:160:15)
at Object.next (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:111:11)
at /Users/candide/work/sekund/solid-build-issues/main_rollup.js:83:65
at new Promise (<anonymous>)
at __awaiter (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:65:9)
at Repro.login (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23664:10)
When debugging the code, it turns out that the crypto constant is not defined. However, at the start of the generated bundle, I can see:
var crypto_1 = require("crypto");
So it looks like my problem basically boils down to rollup redefining global variables when it should not.
Indeed, using the typescript compiler (tsc) on the same source file outputs a perfectly working program.
Here's my rollup config:
import commonjs from "#rollup/plugin-commonjs";
import json from "#rollup/plugin-json";
import { nodeResolve } from "#rollup/plugin-node-resolve";
import typescript from "#rollup/plugin-typescript";
const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/
`;
export default {
input: "src/main.ts",
inlineDynamicImports: true,
output: [
{
file: "main.js",
sourcemap: "inline",
format: "cjs",
exports: "default",
banner,
},
],
external: ["obsidian", "fs", "os", "path"],
plugins: [json(), nodeResolve({ preferBuiltins: true }), commonjs(), typescript({ sourceMap: true })],
};
I created a repro repo at https://github.com/ckemmler/solid-build-issues
man this wrecked my brain for a bit, i managed to find a solution but i don't understand it 100%
please see the solution suggested in this comment https://github.com/uuidjs/uuid/issues/544#issuecomment-740394448
resolved the problem for me

CRA + Yarn 2 + jsconfig.json = Can't run unit tests

I have the following configuration in my jsconfig.json file:
{
"compilerOptions": {
"baseUrl": "./src"
},
"include": ["src"]
}
Which lets me do this:
import { App } from 'components'
import * as actions from 'actions/app.actions'
Instead of this:
import { App } from '../components'
import * as actions from '../actions/app.actions'
To get started with unit testing, I've created a simple App.test.jsx in src/components/tests
import { render } from '#testing-library/react'
import { App } from 'components'
it('renders without crashing', () => {
render(<App />)
})
However, when I run yarn test (which is sugar for react-scripts test), it throws with this ugly error:
FAIL src/components/tests/App.test.jsx
● Test suite failed to run
Your application tried to access components, but it isn't declared in your dependencies;
this makes the require call ambiguous and unsound.
Required package: components (via "components")
Required by: C:\Users\Summer\Code\sandbox\src\components\tests\
23714 | enumerable: false
23715 | };
> 23716 | return Object.defineProperties(new Error(message), {
| ^
23717 | code: { ...propertySpec,
23718 | value: code
23719 | },
at internalTools_makeError (.pnp.js:23716:34)
at resolveToUnqualified (.pnp.js:24670:23)
at resolveRequest (.pnp.js:24768:29)
at Object.resolveRequest (.pnp.js:24846:26)
It seems like Jest (or Yarn?) thinks components is a node package, because it's not aware of the absolute imports setting in my jsconfig.json. Is there a way to make it aware? Or do I have to choose between 0% coverage and relative imports?
I've tried entering "moduleNameMapper" under "jest" in my package.json like the documentation explains, but it didn't help. I got the same error + one more after it.
I've also tried changing components in the test file to ../components but then it complains about actions/app.actions which is inside the <App /> component.
Module name mapper config:
/* package.json */
{
/* ... */
"jest": {
"moduleNameMapper": {
"actions(.*)$": "<rootDir>/src/actions$1",
"assets(.*)$": "<rootDir>/src/assets$1",
"components(.*)$": "<rootDir>/src/components$1",
"mocks(.*)$": "<rootDir>/src/mocks$1",
"pages(.*)$": "<rootDir>/src/pages$1",
"reducers(.*)$": "<rootDir>/src/reducers$1",
"scss(.*)$": "<rootDir>/src/scss$1",
"store(.*)$": "<rootDir>/src/store$1",
"themes(.*)$": "<rootDir>/src/themes$1",
"api": "<rootDir>/src/api.js",
}
}
}
This is because Yarn takes control of the resolution pipeline, and thus isn't aware of resolution directives coming from third-party configuration (like moduleNameMapper).
This isn't to say you have no options, though - specifically, the fix here is to avoid moduleNameMapper, and instead leverage the builtin link: dependency protocol. This has other advantages, such as being compatible with all tools (TS, Jest, ESLint, ...) without need to port your aliases to each configuration format.
See also: Why is the link: protocol recommended over aliases for path mapping?

How to use vuetify in nuxt js as plugin?

I need to use vuetify in my nuxt js project as plugin. I've tried package #nuxtjs/vuetify but get error
Cannot assign to read only property 'base' of object '#'
I've install my nuxt project from official codesandbox online playground in local server and on shared hosting. All the time I got the same error. I tried install node modules using npm and yarn. How I can add fresh vuetify version to last version of nuxt js as plugin with npm package vuetify?
Install vuetify and #mdi/font
Create a file vuetify.js in your plugins folder with the following code:
import Vue from 'vue'
import Vuetify from 'vuetify'
import colors from './../config/colors'
import 'vuetify/dist/vuetify.min.css'
import '#mdi/font/css/materialdesignicons.css'
Vue.use(Vuetify)
export default ctx => {
const vuetify = new Vuetify({
theme: {
themes: {
light: {
...colors
},
dark: {
// colors
}
}
}
})
ctx.app.vuetify = vuetify
ctx.$vuetify = vuetify.framework
}
Edit nuxt.config.js file by adding vuetify to plugins like this
{
...
plugins: ['~plugins/vuetify.js'],
...
}
I achieved this with the following:
npm install --save vuetify
create a file vuetify.js in your plugins folder with the following code:
import Vue from 'vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)
Amend your nuxt.config.js:
plugins: ['~plugins/vuetify.js'],
build: {
vendor: ['vuetify']
}
There is a discussion of this issue here: https://github.com/nuxt-community/vuetify-module/issues/268
Fixing custom colours and specifying options in external files seem to affect this.
If you have colours specified in the options, replace primary: colors.blue with primary: colors.blue.base.
I have / had same issue. I simply made sure to use version 1.10.3 or below defined explicitly in package.json
"#nuxtjs/vuetify": "1.10.3", (not with the ^1.10.3)
I also noticed any version over this also adds an "undefined" 404 to the end of every url request. I posted on Nuxt / CMTY but they have a user base of zero people who answer any questions.
Choose Vuetify as ur UI Framework when initial a Nuxt project
Create a new file in plugins/vuetify.js
import Vue from 'vue'
import Vuetify from 'vuetify'
import colors from 'vuetify/es5/util/colors'
Vue.use(Vuetify)
export default new Vuetify({
theme: {
light: true,
themes: {
light: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
})
Add the plugin config inside nuxt.config.js
export default {
plugins: ['~/plugins/vuetify.js'],
}
Restart server, npm run dev
An image example:
vuetify.js
Done!
you can do the following steps in order and finally use Vuetify components:
1- Setup vuetify
yarn add vuetify#next sass
2- Your package.json should now look similar to the following:
// package.json
"devDependencies": {
"nuxt": "3.0.0-rc.1"
},
"dependencies": {
"sass": "^1.51.0",
"vuetify": "^3.0.0-beta.1"
}
3- Creating your Vuetify plugin
You must create this file in the plugin folder and put these codes inside it.
// plugins/vuetify.js
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
export default defineNuxtPlugin(nuxtApp => {
const vuetify = createVuetify({
components,
directives,
})
nuxtApp.vueApp.use(vuetify)
})
4- Configure Nuxt 2 or 3 to use our new plugin
In this section, you should put these codes in the nuxt.config.ts file like this
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
css: ['vuetify/lib/styles/main.sass'],
build: {
transpile: ['vuetify'],
},
vite: {
define: {
'process.env.DEBUG': false,
},
},
})
5- Finally, in order to test that you have done the steps correctly, you can use this component in your code to see if Vuetify is installed correctly or not.
<v-btn>Button</v-btn>
Tip: If you have done these steps or you want to use a new component, in many cases it is better to stop and restart your project once.

TypeScript AMD compilation and "barrel" modules

I'm trying to set up a Node.js + TypeScript project using Intern for testing. Everything works fine when I compile the project using "commonjs" (which I do for the normal build); and TypeScript is equally happy when compiling for "amd", which is required by Intern. However, when passing the tests with intern-client, it complains about a couple of things:
First, imports from "index.ts" files (so-called "barrel" modules) won't work. My setup is something like this (everything in the same directory):
// index.ts
export { x } from './x'
// x.ts
export function x() {}
// x.test.ts
import { x } from '.' // "Error: Failed to load module ..."
In fact, the generated JavaScript code (for x.test.ts) looks something like this:
define(["require", "exports", "."], function (...) { ... })
And I'm not sure that AMD knows how to handle the ".".
The second issue happens under the same circumstances (TypeScript compiles happily, but intern-client complains). In summary, I get an error when doing:
import jsdom = require('jsdom')
Which I need to transform to:
const jsdom = require('jsdom')
For Intern to be able to deal with it.
Here is the tsconfig.json file I use to compile the tests:
{
"compilerOptions": {
"target": "es6",
"module": "amd",
"moduleResolution": "node",
"sourceMap": true,
"rootDir": "src",
"outDir": "build/tests",
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
And here is my intern.js configuration file, in case it helps:
define({
suites: ['build/tests/**/*.test.js'],
excludeInstrumentation: true,
filterErrorStack: true
})
Edit (2017-05-03)
To help understand the issue, here is an excerpt of the directory tree of the project:
build
tests // The compiled tests will end up here
src
core
utils
x.ts
x.test.ts
// Other files, each containing a function that I would like to unit-test...
intern.js
package.json
tsconfig.json
...
Regarding the first issue, AMD's handling of an import like '.' is different than Node's. While both of them will map '.' to a package, Node uses a default module name of index.js, while AMD uses main.js. To get things working in an AMD loader, you'll need to first define a package for '.', and then tell the AMD loader what default module to use for that package. Given your project layout, you could configure Intern like this:
loaderOptions: {
map: {
// When a module in src/ references 'src/utils', redirect
// it to 'utils'
'src': {
'src/utils': 'utils'
}
},
packages: [
// Define a package 'utils' with files in 'src/utils' that defaults
// to the module index.js
{ name: 'utils', location: 'src/utils', main: 'index.js' }
]
}
Regarding the second issue, its not clear what the problem actually is. Import statements will be transpiled into define dependencies by TypeScript, so Intern should never be seeing them.

How to use codelyzer in angular 2

I want to use codelyzer in my project and i use the systemjs and no webpack.
I added a this tslint to my project and use npm start to run the project but it's didn't get any error from my project even though i didn't use correct style guide in my project
what should I do to use codelyzer?
Codelyzer is already available online at http://codelyzer.com so you can give it a try in your browser!
You can also use it in:
Angular CLI
Angular CLI has support for codelyzer. In order to validate your code with CLI and the custom Angular specific rules just use:
ng new codelyzer
ng lint
Note that by default all components are aligned with the style guide so you won't see any errors in the console.
Angular Seed
Another project which has out of the box integration with codelyzer is angular-seed. In order to run the linter you should:
# Skip if you've already cloned Angular Seed
git clone https://github.com/mgechev/angular-seed
# Skip if you've already installed all the dependencies of Angular Seed
cd angular-seed && npm i
# Run all the tslint and codelyzer rules
npm run lint
Note that by default all components are aligned with the style guide so you won't see any errors in the console.
Custom Setup
You can easily use codelyzer with your custom setup:
Installation
npm i codelyzer tslint typescript #angular/core#2.0.2 #angular/compiler#2.0.2 rxjs#5.0.0-beta.12 zone.js#0.6.21
Now create the following tslint.json file where your node_modules directory is:
{
"rulesDirectory": [
"node_modules/codelyzer"
],
"rules":{
"directive-selector-name": [true, "camelCase"],
"component-selector-name": [true, "kebab-case"],
"directive-selector-type": [true, "attribute"],
"component-selector-type": [true, "element"],
"directive-selector-prefix": [true, "sg"],
"component-selector-prefix": [true, "sg"],
"use-input-property-decorator": true,
"use-output-property-decorator": true,
"use-host-property-decorator": true,
"no-attribute-parameter-decorator": true,
"no-input-rename": true,
"no-output-rename": true,
"no-forward-ref": true,
"use-life-cycle-interface": true,
"use-pipe-transform-interface": true,
"pipe-naming": [true, "camelCase", "sg"],
"component-class-suffix": true,
"directive-class-suffix": true,
"import-destructuring-spacing": true,
"templates-use-public": true,
"no-access-missing-member": true,
"invoke-injectable": true
}
}
Next you can create a component file in the same directory with name component.ts and the following content:
import { Component } from '#angular/core';
#Component({
selector: 'codelyzer',
template: `
<h1>Hello {{ nme }}!</h1>
`
})
class Codelyzer {
name: string = 'World';
ngOnInit() {
console.log('Initialized');
}
}
As last step you can execute all the rules against your code with tslint:
$ ./node_modules/.bin/tslint -c tslint.json component.ts
You should see the following output:
component.ts[4, 13]: The selector of the component "Codelyzer" should have prefix "sg"
component.ts[12, 3]: Implement lifecycle hook interface OnInit for method ngOnInit in class Codelyzer
component.ts[9, 7]: The name of the class Codelyzer should end with the suffix Component
component.ts[6, 18]: The property "nme" that you're trying to access does not exist in the class declaration. Probably you mean: "name".
Editor Configuration
Note that you need to have tslint plugin install on your editor.
Codelyzer should work out of the box with Atom but for VSCode you will have to open Code > Preferences > User Settings, and enter the following config:
{
"tslint.rulesDirectory": "./node_modules/codelyzer",
"typescript.tsdk": "node_modules/typescript/lib"
}
Now you should have the following result:
(source: gifyu.com)

Resources