This may be self-evident but I'm not finding any example that informs what I'm trying to do (maybe I'm just doing it wrong). I'm adding Vue to an existing ASP.NET Core MVC application and adding the JavaScript statements directly to the page works but when I try to migrate to a TypeScript file nothing happens.
The JavaScript is:
new Vue({
el: "#productPage",
data: {
isLoading: true
},
methods: {
},
mounted () {
console.log("mounted()");
this.isLoading = false;
}
});
This works as expected. Migrating the code to a TypeScript file productPage.ts:
import Vue from 'vue';
new Vue({
el: "#productPage",
data: {
isLoading: true
},
methods: {
},
mounted () {
console.log("mounted()");
this.isLoading = false;
}
});
Which generates:
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "vue"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var vue_1 = require("vue");
var HonestyBox;
(function (HonestyBox) {
new vue_1.default({
el: "#productPage",
data: {
isLoading: true
},
methods: {},
mounted: function () {
console.log("Mounted !!!!");
this.isLoading = false;
}
});
})(HonestyBox || (HonestyBox = {}));
});
//# sourceMappingURL=productPage.js.map
And including the generated javascript file productPage.js:
<script src="~/js/productPage.js"></script>
This does nothing. Stepping through the debugger neither of the conditions in function(factory) are satisfied. The console tells me You are running Vue in development mode. but the included JavaScript fails to run. The tsconfig.json used to generate the JavaScript file:
{
"compileOnSave": true,
"compilerOptions": {
"module": "umd",
"moduleResolution": "node",
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": true,
"target": "es5",
"outDir": "wwwroot/js"
},
"include": [
"Typescript/**/*"
],
"exclude": [
"node_modules",
"wwwroot"
]
}
Using "module": "commonjs" results in ReferenceError: exports is not defined. I was hoping to avoid having to use Browserify or Webpack.
If I understand you correctly you add Vue in a separate script tag before your productPage.js.
This means that you can't import Vue in your TypeScript file, but you need to declare Vue so the module just assumes that Vue has been loaded already (outside of your TS module).
declare const Vue; // this replaces your Vue import statement
If you want to add a bundler later on, you need to remove your script tag which loads Vue and only go the modular approach:
Vue needs to be imported with an import statement so the bundler knows that he has to include all of Vue.
You will then have one single JS file (or if your bundler splits it: multiple JS files).
Related
When I prepare DataTable in stimulus controller, it fires twice what is behaviour of turbo (for caching purposes) and therefore I get DataTables error of initializing it twice
When I tried fix as I use in rails6 without stimulus, it does not work
document.addEventListener('turbo:before-cache', function() {
if ($('#invoices_wrapper').length ==1) {invoicetable.destroy() ;} });
If I put console.log inside that function, I see it is not even executed.
How can I properly setup DataTables with stimulus?
This is my code
import { Controller } from "#hotwired/stimulus"
import $ from 'jquery';
import 'jszip';
import datatable from 'datatables.net-bs5';
import 'datatables.net-buttons-bs5';
window.datatable = datatable();
export default class extends Controller {
connect() {
var invoicetable = $('#invoices').DataTable({
'order': [1, 'asc'],
'serverSide': true,
"processing": true,
'ajax' : '/invoices.json',
columns: [
//{data: 'id', searchable: false, orderable: false},
{data: 'name' },
{data: 'value' }
],
initComplete: function ()
{
console.log("done")
}
});
}
}
Added config files to the project (packege.json &webpack.config.json), added babel. At the moment it turns out like this: There is a directory / Scripts / build &Scripts / es6 (/main.js). When the npm run build command is run, everything builds ok (from themain.js file as indicated in the entry section of thewebpack.config.json file), the bundle.js file is created in the/ Scripts / build directory. In the above, there are no problems and everything is as it should. Now I want to use the js classes (their methods and properties) in the views (* .cshtml). How do i do this? Or need a different approach? If I write js code inmain.js, then I build it, then the code fulfills. But how do I make a function and run it (for example, by clicking a button)?
packege.json:
{
"name": "SensorDashboard",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --progress --mode='development' -p"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: ['./Scripts/es6/main.js'],
output: {
path: path.resolve(__dirname, './Scripts/build'),
filename: 'bundle.js'
},
// IMPORTANT NOTE: If you are using Webpack 2 or above, replace "loaders" with "rules"
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
}
}
main.js:
import { Map, MyClass } from './Map';
(function () {
window.test_func = function () {
let cl = new MyClass();
cl.send("asd qweqwe");
};
})();
MyClass:
export class MyClass {
send(message) {
console.log(message);
}
}
then i runing command: npm run build, and a file was created (/Script/build/bundle.js)
then i try to use in *.cshtml:
#{Layout = null;}
...
<script src="~/Scripts/build/bundle.js"></script>
...
<div>....</div>
<script type="text/javascript">
$(document).ready(function () {
test_func(); //this work
let m = new MyClass(); //this don`t work (MyClass is not defined)
m.send("asd");
});
</script>
I think should be as simple as loading the script in your .cshtml file with your standard script tag at the bottom of the file which would look something like this:
#section Scripts {
<script src="#Url.Content("~/Scripts/build/main.js")"></script>
}
(possibly without the #Url.Content though I'm not 100% sure offhand)
You could then call a function by doing something like the following example, there are a few ways and probably depends on what your class looks like in your main.js:
#section Scripts {
<script src="#Url.Content("~/Scripts/build/main.js")"></script>
document.getElementById("myButton").onclick = function(){
let someClass = new Class();
someClass.DoSomething();
}
}
Let me know if I've misunderstood the question.
Edit:
Okay, sorry I did misunderstand.
Have a look at this link and see if it helps you? It looks like exactly what you need.
It has instructions on how to configure webpack to allow calling externally.
Looks as simple as adding these two lines to your output:
libraryTarget: 'var',
library: 'EntryPoint'
Where EntryPoint is the Name you want for the module .
So:
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: 'app.bundle.js',
libraryTarget: 'var',
library: 'MyModule'
},
And that should allow you to just call
EntryPoint.send("asd qweqwe");
Running webpacker 3.5.5 (both the gem and package). This is mostly working, but in IE11 the app is broken because arrow functions do not appear to be transformed. However, inspecting the minified code it seems like the only place arrow functions aren't transformed are inside my vue components.
I think this is because my babel class properties plugin is not applying to my Vue loader somehow, but I haven't been able to come up with a solution.
Here's my .babelrc
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": [
"> 1%",
"IE 11"
],
"uglify": true
},
"useBuiltIns": true
}
]
],
"plugins": [
"syntax-dynamic-import",
"transform-object-rest-spread",
[
"transform-class-properties",
{
"spec": true
}
]
],
"env": {
"test": {
"presets": ["es2015"]
}
}
}
And here's the entirety of my environment.js file that modifies the webpack environment that webpacker ships with (vue loader is at the bottom).
const { environment } = require('#rails/webpacker');
environment.loaders.append('expose', {
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
}]
});
const webpack = require('webpack');
// append some global plugins
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
axios: 'axios',
moment: 'moment-timezone',
_: 'lodash'
}));
// Necesary configuration for vue-loader v15
const VueLoaderPlugin = require('vue-loader/lib/plugin');
environment.plugins.append(
'VueLoaderPlugin',
new VueLoaderPlugin()
);
environment.loaders.append('vue', {
test: /\.vue$/,
loader: 'vue-loader'
});
module.exports = environment;
Edit for more info: Here is the entry point to my pack called 'wrestling'
import 'babel-polyfill';
import 'wrestling';
Then in wrestling.js...
import './styles/wrestling'
import Rails from 'rails-ujs'
Rails.start();
import wrestlingSetup from './wrestlingSetup'
wrestlingSetup();
WrestlingSetup contains the actual references to the vue files. I've cut down the file to show what a single vue import looks like within the file. All the rest are essentially the same.
import Vue from 'vue/dist/vue.esm'
// Redacted a bunch of imports, but they all look like this oen
import WrestlerCreate from './vue/wrestler_create.vue'
export default function() {
document.addEventListener('DOMContentLoaded', () => {
axiosSetup();
const app = new Vue({
el: '#app',
components: {
// Other vue components here that I've removed for simplicity
WrestlerCreate,
}
})
});
}
Here's an actual example of the Vue component
<template>
<div role="form">
<!-- other form elements -->
</div>
</template>
<script>
export default {
name: 'wrestler-create',
props: [
],
// This does not get transformed by babel
data() {
return {
loading: false,
error: false,
errorMessage: "Error, please try again later or contact support.",
first_name: '',
last_name: '',
weight_class: '',
academic_class: ''
}
},
methods: {
// removed for simplicity
}
}
</script>
For clarify sake:
Please use function() for data. I find function() gives me less trouble than arrow functions.
export default {
data: function() {
return {
message: "Hello something!",
secondMessage: "Hello world!"
};
}
}
If you really wish to use arrow function, you can write:
export default {
data: () => {
return {
message: "Hello something!",
secondMessage: "Hello world!"
};
}
}
In my code, I want to import an external javascript file that is common across multiple components. When rollup builds the component, however, it has trouble resolving the imported dependency so it never gets included in the output package. Note, I'm trying to build a svelte component (as opposed to a svelte app) although I'm not sure that makes a difference. Here is my rollup.config.js:
import svelte from 'rollup-plugin-svelte';
import pkg from './package.json';
const name = pkg.name
.replace(/^(#\S+\/)?(svelte-)?(\S+)/, '$3')
.replace(/^\w/, m => m.toUpperCase())
.replace(/-\w/g, m => m[1].toUpperCase());
export default {
input: 'src/Radar.html',
output: [
{ sourcemap: true, file: pkg.module, 'format': 'es' },
{ sourcemap: true, file: pkg.main, 'format': 'umd', name }
],
plugins: [
svelte({
cascade: false,
store: true
})
]
};
To resolve dependency there is a plugin for Rollup:
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import pkg from './package.json';
const name = pkg.name
.replace(/^(#\S+\/)?(svelte-)?(\S+)/, '$3')
.replace(/^\w/, m => m.toUpperCase())
.replace(/-\w/g, m => m[1].toUpperCase());
export default {
input: 'src/Radar.html',
output: [
{ sourcemap: true, file: pkg.module, 'format': 'es' },
{ sourcemap: true, file: pkg.main, 'format': 'umd', name }
],
plugins: [
svelte({
cascade: false,
store: true
}),
resolve()
]
};
I assume that Radar.html is a Svelte module, i.e. you can rename it to Radar.svelte.
I am trying to do a simple ipc.send and ipc.on but for some reason I am getting undefined on this electron require.
libs/custom-menu.js:
'use-strict';
const BrowserWindow = require('electron').BrowserWindow;
const ipcRenderer = require('electron').ipcRenderer;
exports.getTemplate = function () {
const template = [
{
label: 'Roll20',
submenu: [
{
label: 'Player Handbook',
click() {
console.log('test');
},
},
],
},
{
label: 'View',
submenu: [
{
label: 'Toggle Fullscreen',
accelerator: 'F11',
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
}
},
},
{
label: 'Toggle Developer Tools',
accelerator: (function () {
if (process.platform === 'darwin') {
return 'Alt+Command+I';
}
return 'Ctrl+Shift+I';
}()),
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.toggleDevTools();
}
},
},
{
label: 'Reload',
accelerator: 'F5',
click() {
BrowserWindow.getFocusedWindow().reloadIgnoringCache();
},
},
],
},
{
label: 'Random Generators',
submenu: [
{
label: 'World Generator',
click() {
ipcRenderer.send('show-world');
},
},
],
},
];
return template;
};
The error is
cannot read property 'send' of undefined.
The BrowserWindow module is only available in the main process, the ipcRenderer module is only available in the renderer process, so regardless of which process you run this code in it ain't gonna work. I'm guessing since ipcRenderer is not available you're attempting to run this code in the main process.
I know this answer might have been too late for you but for other
If you're trying access any of main process modules from renderer process you will need to go through remote module,
const {BrowserWindow} = require('electron').remote
see documentation remote
Just for those who can't get this to work in react app ipcRenderer or in any environment that requires preload file.
preload setup
These lines worked for me:
app.commandLine.appendSwitch('ignore-certificate-errors', 'true')
app.commandLine.appendSwitch('allow-insecure-localhost', 'true')
In the renderer process, the script tags that have the "require" statement needs to be:
<script type="javascript"></script>
Placing your call to require in a script tag without the type set doesn't work.