I was trying to implement Monaco Editor in Vue 3 application but I could not get the web worker running.
// Editor.vue
<template>
<div id="container">
<div id="editor-section"></div>
<button #click="runCode">Run</button>
</div>
</template>
<script>
import * as monaco from "monaco-editor";
import { onMounted } from "vue";
export default {
name: "Editor",
setup() {
let codeEditor = null;
function initEditor() {
codeEditor = monaco.editor.create(document.getElementById("editor-section"), {
value: "function hello() {\n\talert('Hello world!');\n}",
language: "javascript",
theme: "vs-dark"
});
}
function runCode() {
console.log("runCode");
console.log(codeEditor.getValue());
}
onMounted(() => {
initEditor();
})
return { codeEditor, runCode }
},
};
</script>
I am getting the Editor but there is this issue
I am using
// vue.config.js
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");
module.exports = {
plugins: [
new MonacoWebpackPlugin()
]
};
Am I missing anything?
Should I care about the Issue anyway?
My goal of the project is I want to implement a web editor that takes the written file and compiles in docker container.
It looks like you put the plugin in the wrong place. It's supposed to be placed in configureWebpack which represents for webpack configuration instead:
vue.config.js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new MonacoWebpackPlugin(), // Place it here
]
},
// ...
}
Related
I have a problem with Vue 3, using vue from CDN.
I want to use a template generated by the server, the template is changed but methods and data are not bound.
<script>
// reproduction of the issue in vue3 vite
import { compile, computed, h } from 'vue/dist/vue.esm-bundler'; // vite
// import { compile, computed, h } from 'vue/dist/vue.esm-bundler'; // webpack
export default {
data() {
return {
htmlTemplate: '<span #click="test()">this is a test {{ testVariable }}</span>', // This is a test from what would be loaded from the server
testVariable: 'test variable',
}
},
methods: {
test() {
console.log('test');
}
},
render() {
const textCompRef = computed(() => ({ render: compile(this.htmlTemplate) }));
console.log('textCompRef', textCompRef);
return h(textCompRef.value);
}
}
</script>
When I click on this is a test then vue#3:1807 Uncaught TypeError: test is not a function
Can someone point me in the right direction?
Thanks in advance
I tried setting the template in the create life cycle with this.$options.template = response from the server that worked on 3-rd click and was not changing when new template is loaded.
I am currently trying to implement a feature where a user can select a language from a dropdown menu in a Settings page (SettingsDialog.vue), updating all of the text to match the new language. This application has multiple Vue files like a MenuBar.vue, HelpDialog.vue, each pulling from translation.ts for their English translations. However, I noticed that selecting a language from the dropdown menu only changed the elements inside my SettingsDialog.vue file, not all of the other Vue files I have.
I tried using the Vue-I18n documentation implementation of changing locale globally in the file. I was expecting for the locale of the entire application to change after selecting a language in SettingsDialog.vue, applying my English translations in translation.ts to the Menu Bar, Help Page, etc. What happened is that the translations from translation.ts only applied to the SettingsDialog.vue page, no where else.
I guess it would be helpful to add that this is an Electron application, and the Vue files in the project use Quasar. Each file does have the correct import statements.
main.ts:
// ...
window.datalayer = [];
const i18n = createI18n({
legacy: false,
locale: "",
messages,
});
createApp(App)
.use(store, storeKey)
.use(router)
.use(
createGtm({
id: process.env.VUE_APP_GTM_CONTAINER_ID ?? "GTM-DUMMY",
vueRouter: router,
enabled: false,
})
)
.use(Quasar, {
config: {
brand: {
primary: "#a5d4ad",
secondary: "#212121",
},
},
iconSet,
plugins: {
Dialog,
Loading,
},
})
.use(ipcMessageReceiver, { store })
.use(markdownItPlugin)
.use(i18n)
.mount("#app");
SettingsDialog.vue
// ...
<!-- Language Setting Card -->
<q-card flat class="setting-card">
<q-card-actions>
<div id="app" class="text-h5">{{ $t("言語") }}</div>
</q-card-actions>
<q-card-actions class="q-px-md q-py-sm bg-setting-item">
<div id="app">{{ $t("言語を選択する") }}</div>
<q-space />
<q-select
filled
v-model="locale"
dense
emit-value
map-options
options-dense
:options="[
{ value: 'ja', label: '日本語 (Japanese)' },
{ value: 'en', label: '英語 (English)' },
]"
label="Language"
>
<q-tooltip
:delay="500"
anchor="center left"
self="center right"
transition-show="jump-left"
transition-hide="jump-right"
>
Test
</q-tooltip>
</q-select>
</q-card-actions>
</q-card>
// ...
<script lang="ts">
import { useI18n } from "vue-i18n";
// ...
setup(props, { emit }) {
const { t, locale } = useI18n({ useScope: "global" });
// ...
return {
t,
locale,
// ...
};
MenuBar.vue
<template>
<q-bar class="bg-background q-pa-none relative-position">
<div
v-if="$q.platform.is.mac && !isFullscreen"
class="mac-traffic-light-space"
></div>
<img v-else src="icon.png" class="window-logo" alt="application logo" />
<menu-button
v-for="(root, index) of menudata"
:key="index"
:menudata="root"
v-model:selected="subMenuOpenFlags[index]"
:disable="menubarLocked"
#mouseover="reassignSubMenuOpen(index)"
#mouseleave="
root.type === 'button' ? (subMenuOpenFlags[index] = false) :
undefined
"
/>
// ...
<script lang="ts">
import { defineComponent, ref, computed, ComputedRef, watch } from "vue";
import { useStore } from "#/store";
import MenuButton from "#/components/MenuButton.vue";
import TitleBarButtons from "#/components/TitleBarButtons.vue";
import { useQuasar } from "quasar";
import { HotkeyAction, HotkeyReturnType } from "#/type/preload";
import { setHotkeyFunctions } from "#/store/setting";
import {
generateAndConnectAndSaveAudioWithDialog,
generateAndSaveAllAudioWithDialog,
generateAndSaveOneAudioWithDialog,
} from "#/components/Dialog";
import { useI18n } from "vue-i18n";
import messages from "../translation";
type MenuItemBase<T extends string> = {
type: T;
label?: string;
};
export type MenuItemSeparator = MenuItemBase<"separator">;
export type MenuItemRoot = MenuItemBase<"root"> & {
onClick: () => void;
subMenu: MenuItemData[];
};
export type MenuItemButton = MenuItemBase<"button"> & {
onClick: () => void;
};
export type MenuItemCheckbox = MenuItemBase<"checkbox"> & {
checked: ComputedRef<boolean>;
onClick: () => void;
};
export type MenuItemData =
| MenuItemSeparator
| MenuItemRoot
| MenuItemButton
| MenuItemCheckbox;
export type MenuItemType = MenuItemData["type"];
export default defineComponent({
name: "MenuBar",
components: {
MenuButton,
TitleBarButtons,
},
setup() {
const { t } = useI18n({
messages,
});
// ...
};
const menudata = ref<MenuItemData[]>([
{
type: "root",
label: t("ファイル"),
onClick: () => {
closeAllDialog();
},
// ...
]);
translation.ts
const messages = {
en: {
// MenuBar.vue
ファイル: "File",
エンジン: "Engine",
ヘルプ: "Help",
// SettingDialog.vue
言語: 'Language',
言語を選択する: 'Select Language',
オフ: 'OFF',
エンジンモード: 'Engine Mode',
// HelpDialog.vue
ソフトウェアの利用規約: 'test',
}
};
export default messages;
Maybe there are more problems but now I see two:
Your menudata should be computed instead of just ref. Right now you are creating a JS object and setting it label property to result of t() call. When global locale changes this object is NOT created again. It still holds same value the t() function returned the only time it was executed - when setup() was running
// correct
const menudata = computed<MenuItemData[]>(() => [
{
type: "root",
label: t("ファイル"),
onClick: () => {
closeAllDialog();
},
// ...
]);
This way whenever i18n.global.locale changes, your menudata is created again with new translation
As an alternative, set label to key and use t(label) inside the template. However computed is much more effective solution...
You don't need to pass messages to useI18n() in every component. Only to the global instance. By passing config object into a useI18n() in a component you are creating Local scope which makes no sense if you are storing all translations in a single global place anyway
I use vue3 with composition api, but when I build my project, the ref element always undefined.
I reproduced it, maybe I used it incorrectly, but I don't know why.
I defined a ref in hooks function.
const isShow = ref(false)
const rootRef = ref<HTMLDivElement>();
export default function () {
function changeShow() {
isShow.value = !isShow.value;
console.log(isShow.value, rootRef.value);
}
return { isShow, rootRef, changeShow };
}
Use rootRef in the HelloWorld.vue and linked element.
<script setup lang="ts">
import useShow from "../composables/useShow";
const { rootRef, isShow } = useShow();
</script>
<template>
<div ref="rootRef" v-show="isShow" class="test"></div>
</template>
Create a button in App.vue and bind click function.
<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue";
import useShow from "./composables/useShow";
const { changeShow } = useShow();
</script>
<template>
<button #click="changeShow">切换</button>
<HelloWorld />
</template>
When I click button, it works.
But when I build it and import from lib, it doesn't work.
My vite.config.ts is as follows:
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"#": path.resolve(__dirname, "src")
}
},
build: {
cssCodeSplit: true,
sourcemap: true,
lib: {
entry: path.resolve(__dirname, "src/index.ts"),
name: "my-project",
fileName: format => `my-project.${format}.js`
},
rollupOptions: {
external: ["vue"],
preserveEntrySignatures: "strict",
output: {
globals: {
vue: "Vue"
}
}
}
}
});
I think the problem is the definition of rootRef. It seems that only binding location can use it. This is no different from defining it in a component. I need to use it in multiple places.
Oddly, in this way, the Dev environment works fine, but Pro env is not available. Do I need to modify the build configuration of vite.
How do I do that?
The problem is your App.vue uses its own copy of composables/useShow instead of the one from the lib.
The solution is to export the composable from the lib so that your app can use the same one:
// src/index.ts
import { default as useShow } from './composables/useShow';
//...
export default {
//...
useShow
};
In App.vue, use the lib's composable:
import MyProject from "../dist/my-project.es";
const { changeShow } = MyProject.useShow();
GitHub PR
I'm creating an app with MFE with Vuejs3 and webpack 5 module federation. One main app made with Vue will consume other apps (should be framework agnostic) and I need to share State from my Vue shell to other apps.
I tried making a store with the Composition api but the value get only updated in the app that call the event.
Here is the store that I expose from the vue shell:
import { reactive, toRefs } from 'vue'
const state = reactive({
data: {
quantity: 1,
},
})
export default function useStoreData() {
const updateQuantity = (quantity) => {
state.data.quantity += quantity
}
return {
...toRefs(state),
updateQuantity,
}
}
in vue shell :
<template>
<div>
<button #click="updateQuantity(1)">FOO +1</button>
<div>Quantity = {{ data.quantity }} </div>
</div>
</template>
<script setup>
import useStoreData from '../store/storeData'
const { updateQuantity, data } = useStoreData()
</script>
when I click on the button "FOO +1", value gets updated +1.
in my remote app:
<template>
<div>
<button #click="updateQuantity(5)">BAR +5</button>
<div>Quantity = {{ data.quantity }}</div>
</div>
</template>
<script setup>
import store from 'store/storeData'
const useStoreData = store
const { data, updateQuantity } = useStoreData()
</script>
When i click on button "BAR +5" the value get update +5
BUT everytime I click on one of those button, the value in the other app doesn't get updated.
What did I miss ?
Needed to add the shell app as a remote of itself then import the store in the shell app, same way as i'm doing in my remote app.
Here is the vue.config.js of the shell, where I need to expose AND remote the store.
const { ModuleFederationPlugin } = require('webpack').container
const deps = require('./package.json').dependencies
module.exports = {
publicPath: '/',
configureWebpack: {
plugins: [
new ModuleFederationPlugin({
name: 'shell',
filename: 'remoteEntry.js',
remotes: {
test: 'test#http://localhost:8081/remoteEntry.js',
test2: 'test2#http://localhost:8082/remoteEntry.js',
store: 'shell#http://localhost:8080/remoteEntry.js', <= ADDED HERE the remote of itself
},
exposes: {
'./storeData': './src/store/storeData.js',
},
shared: [
{
...deps,
},
],
}),
],
},
devServer: {
port: 8080,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
},
}
In the Vue shell app:
<script setup>
// import useStoreData from '../store/storeData' <= wrong
import store from 'store/storeData' <= good
</script>
I'm writing a couple of examples for work, and one that's hanging me up is injecting a service that's provided during Vue's bootstrapping.
This "works" (I can access it, it compiles, and runs), and there are no problems or complaints with my JavaScript version nor the Class-Component TypeScript version, but the compiler complains that this.sampleService doesn't exist in my component when using the Vue object API with TypeScript.
Am I missing something?
<template>
<div class="app">
{{message}} <fake-button :text="buttonText" #some-click-event="handleClickEvent"></fake-button>
</div>
</template>
<style lang="scss">
.app {
$background-color: #9f9;
$foreground-color: #000;
background: $background-color;
color: $foreground-color;
}
</style>
<script lang="ts">
import Vue from 'vue'
const App = Vue.extend({
components: {
FakeButton: () => import('#client/components/fake-button/fake-button-object-typescript.vue')
},
data: function () {
return {
message: 'Hello World - App Object TypeScript',
buttonText: 'Click Me'
}
},
inject: {
sampleService: 'sampleService'
},
methods: {
handleClickEvent(someVal?: string) {
console.log('App', 'handleClickEvent', someVal);
}
},
beforeCreate() {
console.log('App', 'beforeCreate');
},
created() {
console.log('App', 'created');
},
mounted() {
console.log('App', 'mounted');
// TODO: While this compiles, TypeScript complains that it doesn't exist
console.log('this.sampleService.getDate()', this.sampleService.getDate());
}
});
export default App;
</script>
ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts
[tsl] ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts(35,56)
TS2339: Property 'sampleService' does not exist on type 'CombinedVueInstance<Vue, { message: string; buttonText: string; }, { handleClickEvent(someVal?: s...'.
My solution for this problem was to create a interface for the injection. In you example that would be something like the follwing:
<script lang="ts">
import { SampleServiceInjection } from '...';
const App = ( Vue as VueConstructor<Vue & SampleServiceInjection> ).extend({
inject: {
sampleService: 'sampleService'
} as Record<keyof SampleServiceInjection, string>,
// etc.
});
</script>
You can use that very interface in component that provides the service as well:
export interface SampleServiceInjection {
sampleService: SampleService; // or whatever type your service has
}
export default Vue.extend({
provide(): SampleServiceInjection {
return {
sampleService: new SampleService(),
};
},
// etc.
});
Try adding provide. Check example below. I would suggest using vue-property-decorator since your are leveraging typescript.
inject: {
sampleService: 'sampleService'
},
provide () {
return {
sampleService: this.sampleService,
}
}