How to load local JavaScript file with JSDOM? - javascript

I am unable to use JSDOM (version 13.0.0) to load scripts from the local filesystem with a relative path.
I have taken a look at the following questions but they do not answer my question:
jsdom can't load local html and javascript (I have already followed the runScripts and resources suggestion there).
File foo.js:
var jsdom = require('jsdom')
var html = `<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="bar.js"></script>
</head>
<body>
<div>Test</div>
</body>
</html>`
global.window = new jsdom.JSDOM(html, { runScripts: "dangerously", resources: "usable" }).window
console.log('foo')
File bar.js:
console.log('bar')
Here is the error I get:
$ node foo.js
foo
Error: Could not load script: "bar.js"
at onErrorWrapped (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/resources/per-document-resource-loader.js:41:19)
at Object.check (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/resources/resource-queue.js:72:23)
at request.then.catch.err (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/resources/resource-queue.js:124:14)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:746:11)
at startup (internal/bootstrap/node.js:240:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:564:3) Error: Tried to fetch invalid URL bar.js
at ResourceLoader.fetch (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/resources/resource-loader.js:84:29)
at PerDocumentResourceLoader.fetch (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/resources/per-document-resource-loader.js:16:42)
at HTMLScriptElementImpl._fetchExternalScript (/Users/lone/so/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js:92:30)
at HTMLScriptElementImpl._eval (/Users/lone/so/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js:161:12)
at HTMLScriptElementImpl._poppedOffStackOfOpenElements (/Users/lone/so/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js:126:10)
at OpenElementStack.pop (/Users/lone/so/node_modules/jsdom/lib/jsdom/browser/htmltodom.js:17:12)
at Object.endTagInText [as END_TAG_TOKEN] (/Users/lone/so/node_modules/parse5/lib/parser/index.js:2153:20)
at Parser._processToken (/Users/lone/so/node_modules/parse5/lib/parser/index.js:657:55)
at Parser._processInputToken (/Users/lone/so/node_modules/parse5/lib/parser/index.js:684:18)
at Parser._runParsingLoop (/Users/lone/so/node_modules/parse5/lib/parser/index.js:440:18)
How can I load a local JavaScript file while using JSDOM?

JSDOM doesn't know where to look for that file locally while executing. So running your example you can follow any of this two approaches.
1st Approach
You have to wait for the script file to load and execute.
Create a three files index.html,index.js and test.js into the same folder.
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
abc
<script src='index.js'></script>
</body>
</html>
index.js
document.body.textContent = 123;
test.js
'use strict';
const { JSDOM } = require('jsdom');
const options = {
resources: 'usable',
runScripts: 'dangerously',
};
JSDOM.fromFile('index.html', options).then((dom) => {
console.log(dom.window.document.body.textContent.trim());
setTimeout(() => {
console.log(dom.window.document.body.textContent.trim());
}, 5000);
});
// console output
// abc
// 123
2nd Approach
Set the external scripts base root folder in JSDOM env.
js/index.js
console.log('load from jsdom');
var loadFromJSDOM = 'load from jsdom';
test.js
'use strict';
const { JSDOM } = require('jsdom');
JSDOM.env({
html: "<html><body></body></html>",
documentRoot: __dirname + '/js',
scripts: [
'index.js'
]
}, function (err, window) {
console.log(window.loadFromJSDOM);
}
);
Read more from these references
https://github.com/jsdom/jsdom/issues/1867
jsdom.env: local jquery script doesn't work

Great answer from front_end_dev. It helped me a lot and I will share how my code works with this solution to be more clear. Maybe will help others.
import "#testing-library/jest-dom";
import { logDOM } from "#testing-library/dom";
import { JSDOM } from "jsdom";
import fs from "fs";
import path from "path";
const html = fs.readFileSync(path.resolve(__dirname, "../index.html"), "utf8");
let dom;
let container;
jest.dontMock("fs");
function waitForDom() {
return new Promise((resolve) => {
dom = new JSDOM(html, {
runScripts: "dangerously",
resources: "usable",
url: `file://${path.resolve(__dirname, "..")}/index.html`,
});
dom.window.document.addEventListener("DOMContentLoaded", () => {
resolve();
});
});
}
beforeAll(() => waitForDom());
beforeEach(() => {
container = dom.window.document.body;
});
afterEach(() => container = null)
it("should ", () => {
logDOM(container);
});

Related

Import function only (not entire file stack) into Angular from vanilla JavaScript

The Challenge
I am working on an Electron/Angular app that will display an emergency message to multiple computers in the event of a tornado or other incident. To accomplish this, I am using a WebSocket protocol (Signral R) on the backend to send the alert, which then triggers Electron's main.js (running in the background) to launch a window on any devices running the app.
The arrival of the message triggers the window to launch, but I also need to use the message in the Angular part of the app (which does not initialize until after the window is open) to indicate the nature of the emergency. To avoid timing problems, I planned to import a function into my app.component.ts that would be called at ngOnInit to retrieve an emergency variable from main.js.
The Problem
Angular does not like the import from raw JavaScript. Intuitively you would think Angular would only import the exported class. However it appears to try and import Electron as well (generating a conflict with 'fs' and 'path' that is explained here), generating the following error message:
./node_modules/electron/index.js:1:11-24 - Error: Module not found: Error: Can't resolve 'fs' in 'C:\Users\me\electron-app\node_modules\electron'
./node_modules/electron/index.js:3:13-28 - Error: Module not found: Error: Can't resolve 'path' in 'C:\Users\me\electron-app\node_modules\electron'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
In spite of doing considerable research, I have not found anything approaching a solution. Any ideas for only importing the information I want would be much appreciated. Here are my files:
main.js (simplified somewhat)
const signalR = require("#microsoft/signalr")
const { app, shell, BrowserWindow, Menu, nativeImage, Tray } = require('electron')
const path = require("path");
const url = require("url");
//various setup logic goes here
//...
webSocketConnection.on("EmergencyActivation", (jsonData) => {
createElectronWindow();
const emergencyMessage = jsonData
});
module.exports = class Emergency {
getEmergency() {
return emergencyMessage
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Emergency } from './../../main';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private emergency: Emergency) {}
ngOnInit() {
console.log(this.emergency.getEmergency())
}
}
Though I do not use Angular, I think the issue is communication between your main process and your render process (or
lack
thereof).
Don't try to communicate between processes by importing from the main process to the render process (which can't
be done). Instead, use Inter-Process Communication.
IE: Once an emergency message has been received via webSocket, create the window and then send an IPC message to that newly
created window.
I have needed to "mock" your webSocketConnection functionality for the sake of the below example.
main.js (main process)
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const nodePath = require('path');
let window;
function createWindow() {
window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
listenForEmergency();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
// Mock of "webSocketConnection.on" function (for testing only)
function listenForEmergency() {
let message = 'Emergency: We have no beer'
console.log('Wait 5 seconds before "receiving" emergency message'); // Testing
setTimeout(() => { showEmergencyWindow(message); }, 5000);
}
// Create window and send message via IPC
function showEmergencyWindow(message) {
window = createWindow();
window.webContents.send('emergency', message); // <-- Use of IPC messaging
}
// Create window and send message via IPC
// webSocketConnection.on("EmergencyActivation", (jsonData) => {
// window = createWindow();
// window.webContents.send('emergency', jsonData); // <-- Use of IPC messaging
// });
preload.js (main process)
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
contextBridge.exposeInMainWorld(
'electronAPI', {
emergency: (message) => {
ipcRenderer.on('emergency', message)
}
});
index.html (render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Emergency</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
</head>
<body>
<h1>Emergency</h1>
<div id="message"></div>
</body>
<script>
window.electronAPI.emergency((event, message) => {
document.getElementById('message').innerText = message;
})
</script>
</html>

electron js - cannot get button to perform simple actions from click

Long story short I am working on a single page application that sends commands over a local network. Testing out Electron JS and I can't even seem to get a simple button to work. I feel like I am not linking the logic between main.js and index.js somehow but for the life of me I cannot figure out the correct way to do it. I have even put breakpoints in index.js and through main.js & index.html but none of the breakpoints are hit aside from the ones in main.js. I put a simple function in a preload.js file and that function is correctly called but the one I am trying to attach to a button located in index.html and index.js is never even being hit. A lot of the commented out code is things I want to remember or things I have noticed a different method of creating and just wanted to try and see if that worked. If anyone has any answers or guidance it would be greatly appreciated! :D
Below is my main.js
//#region ---for dev only | hot reload
try {
require('electron-reloader')(module)
} catch (_) {}
//#endregion
const electron = require('electron');
const {app, BrowserWindow, Menu} = require('electron');
const path = require('path');
const ipcMain = electron.ipcMain;
//#region globals
const SRC_DIR = '/src/'
const IMG_DIR = '/assets/images'
//#endregion
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
//frame: false,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
//Used to auto open dev tools for debugging
//win.openDevTools();
win.loadFile('src/index.html');
// win.loadURL(url.format({
// pathname: path.join(__dirname, 'index.html'),
// protocol: 'file',
// slashes: true
// }));
}
app.whenReady().then(() => {
//nativeTheme.shouldUseDarkColors = true;
createWindow();
})
//closes app processes when window is closed
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
})
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{label: 'Edit'},
{type: 'separator'},
{
label: 'Exit',
click() {
app.quit();
}
}
]
}
])
Menu.setApplicationMenu(menu);
Here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Ecas Software</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p id="myText">Let's get started :)</p>
<button id="myBtn">Change Text</button>
<script type="text/javascript" src="./index.js" ></script>
</body>
</html>
Lastly here is my index.js (aka my first and only renderer?)
const electron = require('electron');
const chgBtn = document.getElementById('myBtn');
function replaceText(selector, text){
const element = document.getElementById(selector);
if (element) element.innerText = text;
}
chgBtn.onclick = function() {
replaceText('myText', 'no boom...');
}
// chgBtn.addEventListener('click', function(){
// // if (document.getElementById('myText').innerText == 'boom'){
// // replaceText('myText','no boom...');
// // } else {
// // replaceText('myText','boom');
// // }
// document.alert("working function");
// });
//chgBtn.addEventListener('click', replaceText('myText','no boom...'));
Why you have this error
The problem here is that you didn't use your scripts files the way Electron was intended.
If you use the Devtools Console (by uncommenting win.openDevTools()), you should see this error in your console :
Uncaught ReferenceError: require is not defined (from index.js file)
This is because your index.js file is loaded as a "normal javascript file". If you want to use the Node syntaxe (aka the "require" syntaxe), you need to do it in your preload script. Only the preload script can use the require syntaxe, since it is the only script allowed by Electron to use Node.
You can also use other javascripts files, by import it in your HTML as you did for the index.js file, but you should remove the require call. As the "require" call (on the first line) will throw and error, all the following code will not run. This is why your button did not react on click.
The correct way to do it
If you need to use some methods from the Electron Renderer API (such as the ipcRenderer), you need to put it in your preload script.
If you want to use your own script, in a separate file, you can also do it, you will not be able to directly call Electron API. There is a solution if you want to call the Electron API in your own script, it is called the Context Bridge. This allows you to create an object in your preload script, that can use the Electron API. You can give this object a name, and then call it from your others script by using the window global object.
For example, if you want to use ipcRenderer.send(channel, payload) :
// Preload script
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('theNameYouWant',
{
send: (channel, payload) => ipcRenderer.send(channel, payload)
}
)
// index.js file, imported in your HTML file
window.theNameYouWant.send("channel-name", { someData: "Hello" })
In your example
// Add this in your main.js file to see when a user click on the button from main process
ipcMain.on("button-clicked", (event, data) => console.log(data))
// Preload script
const { contextBridge, ipcRenderer } = require("electron")
contextBridge.exposeInMainWorld("electron", {
send: (channel, payload) => ipcRenderer.send(channel, payload),
})
// index.js
const chgBtn = document.getElementById("myBtn")
function replaceText(selector, text) {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
chgBtn.onclick = function () {
replaceText("myText", "no boom...")
window.electron.send("button-clicked", { someData: "Hello" })
}

getting Syntax error on Chrome and Firefox

I am trying to follow tutorial on how to display WebViewer for pdf. However I get this error
Uncaught SyntaxError: redeclaration of const docViewerindex.html:23:14note: Previously declared at line 20, column 12index.html:20:12
I can see that there is wrong redeclaration however I I am new to this and I have no idea how to fix it. Can someone please advise, I am completely new to this
Based on this
I had a look on this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Redeclared_parameter and. tried to change const to let but that still doesn't help
<!DOCTYPE html>
<html>
<head>
<title>Basic WebViewer</title>
</head>
<!-- Import WebViewer as a script tag -->
<script src='WebViewer/lib/webviewer.min.js'></script>
<body>
<div id='viewer' style='width: 1024px; height: 600px; margin: 0 auto;'></div>
<script>
WebViewer({
path: 'WebViewer/lib', // path to the PDFTron 'lib' folder on your server
licenseKey: 'Insert commercial license key here after purchase',
initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/webviewer-demo.pdf',
// initialDoc: '/path/to/my/file.pdf', // You can also use documents on your server
}, document.getElementById('viewer'))
.then(instance => {
const docViewer = instance.docViewer;
const annotManager = instance.annotManager;
docViewer.on('documentLoaded', () => {});
});
</script>
</body>
</html>
try:
.then(instance => {
const annotManager = instance.annotManager;
instance.docViewer.on('documentLoaded', () => {});
});
the is what solved it
.then(instance => {const { docViewer, annotManager } = instance;
docViewer.on('documentLoaded', () => {});

Using the electron ipcRenderer from a front-end javascript file

I'm in the process of learning to use Electron, and while trying to have my application communicate with the front end I am aware I need to use the ipcRenderer to gain a reference to the DOM elements and then pass that information to ipcMain.
I tried to follow much of the advice suggested here and here, but both of these examples use require('electron').ipcMain and whenever I try to include my script that will be interacting with the front-end into my HTML, nothing occurs since Uncaught ReferenceError: require is not defined. I've been searching for a few hours and haven't had any luck finding a solution - so clearly I'm doing something wrong.
My main.js is very simple, I just create my window and then I create an ipc listener as so:
const { app, BrowserWindow } = require("electron");
const ipc = require('electron').ipcMain;
function createWindow() {
const window = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
center: true,
width: 410,
height: 550,
});
window.loadFile("index.html");
}
app.whenReady().then(createWindow);
ipc.on('invokeAction', (event, data) => {
var result = "test result!";
event.sender.send('actionReply', result);
})
Within the file that I wish to manipulate the DOM with, I attempt to get the element ID and then add an event listener as seen here:
const ipc = require('electron').ipcRenderer;
const helper = require("./api");
var authenticate_button = ipcRenderer.getElementById("authenticate-button");
var authButton = document.getElementById("authenticate-button");
authButton.addEventListener("click", () => {
ipc.once('actionReply', (event, response) => {
console.log("Hello world!");
})
ipc.send('invokeAction');
});
function onAuthenticateClick() {
helper.authenticateLogin(api_public, api_secret, access_public, access_secret);
}
and finally, my HTML only consists of a button that I wish to attach my event listener to:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Project Test</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="main-container">
<button id="authenticate-button" type="submit" onclick="">Authenticate</button>
<p id="status-label">Not Authenticated</p>
</div>
<script src="script.js"></script>
</body>
</html>
If anyone could help point me in the right direction as to how to get this basic functionality to work, it would be very helpful!
As mentioned by AlekseyHoffman, the reason you can't access ipcRenderer in your frontend js file is because you have nodeIntegration set to false. That said, there's a reason it's set to false by default now; it makes your app far less secure.
Let me suggest an alternate approach: rather than trying to access ipcRenderer directly from your frontend js by setting nodeIntegration to true, access it from preload.js. In preload.js, you can selectively expose ipcMain functions (from your main.js file) you want to access on the frontend (including those that can send data back from main.js), and call them via ipcRenderer there. In your frontend js, you can access the preload.js object that exposes those functions; preload.js will then call those main.js functions via ipcRenderer and return the data back to the frontend js that called it.
Here's a simple, but fully working example (these files should be sufficient to build an electron app with two-way communication between main.js and frontend. In this example, all of the following files are in the same directory.):
main.js
// boilerplate code for electron..
const {
app,
BrowserWindow,
ipcMain,
contextBridge
} = require("electron");
const path = require("path");
let win;
/**
* make the electron window, and make preload.js accessible to the js
* running inside it (this will allow you to communicate with main.js
* from the frontend).
*/
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false,
preload: path.join(__dirname, "./preload.js") // path to your preload.js file
}
});
// Load app
win.loadFile(path.join(__dirname, "index.html"));
}
app.on("ready", createWindow);
// end boilerplate code... now on to your stuff
/**
* FUNCTION YOU WANT ACCESS TO ON THE FRONTEND
*/
ipcMain.handle('myfunc', async (event, arg) => {
return new Promise(function(resolve, reject) {
// do stuff
if (true) {
resolve("this worked!");
} else {
reject("this didn't work!");
}
});
});
Note, I'm using an example of ipcMain.handle because it allows two-way communication and returns a Promise object - i.e., when you access this function from the frontend via preload.js, you can get that Promise back with the data inside it.
preload.js:
// boilerplate code for electron...
const {
contextBridge,
ipcRenderer
} = require("electron");
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
// end boilerplate code, on to your stuff..
/**
* HERE YOU WILL EXPOSE YOUR 'myfunc' FROM main.js
* TO THE FRONTEND.
* (remember in main.js, you're putting preload.js
* in the electron window? your frontend js will be able
* to access this stuff as a result.
*/
contextBridge.exposeInMainWorld(
"api", {
invoke: (channel, data) => {
let validChannels = ["myfunc"]; // list of ipcMain.handle channels you want access in frontend to
if (validChannels.includes(channel)) {
// ipcRenderer.invoke accesses ipcMain.handle channels like 'myfunc'
// make sure to include this return statement or you won't get your Promise back
return ipcRenderer.invoke(channel, data);
}
},
}
);
renderer process (i.e. your frontend js file - I'll call it frontend.js):
// call your main.js function here
console.log("I'm going to call main.js's 'myfunc'");
window.api.invoke('myfunc', [1,2,3])
.then(function(res) {
console.log(res); // will print "This worked!" to the browser console
})
.catch(function(err) {
console.error(err); // will print "This didn't work!" to the browser console.
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Electron App</title>
</head>
<body>
<h1>Hello Beautiful World</h1>
<script src="frontend.js"></script> <!-- load your frontend script -->
</body>
</html>
package.json
{
"name": "myapp",
"main": "main.js",
"scripts": {
"start": "electron ."
}
}
The files above should be sufficient to have a fully working electron app with communication between main.js and the frontend js. Put them all in one directory with the names main.js, preload.js, frontend.js, and index.html, and package.json and launch your electron app using npm start. Note that in this example I am storing all the files in the same directory; make sure to change these paths to wherever they are stored on your system.
See these links for more info and examples:
Electron documentation on inter-process communication
An overview of why IPC is needed and the security issues of setting nodeintegration to true
The require is not defined because you didn't enable nodeIntegration on the window. Set it to true in your window config:
const window = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
center: true,
width: 410,
height: 550,
webPreferences: {
nodeIntegration: true
}
})

Read file inside current directory using Vue

I'm trying to get text file data located in the same directory where my .vue file is. But it's not returning the text on both chrome and firefox. Instead it's returning following response, which is not the content of my text file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>router-project</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="text/javascript" src="/app.js"></script></body>
</html>
Following is my vue file.
<template>
<body>
<div> hello world </div>
</body>
</template>
<script>
var $ = require('jquery');
window.jQuery = $;
export default {
data () {
return {
}
},
created () {
this.getPoemList(),
},
methods: {
getPoemList () {
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "hello.txt");
oReq.send();
} // getPoemList function ends
} // methods end
} // export default ends
</script>
<style scoped>
</style>
Contents of hello.txt are following.
hello
I assume you're using Webpack, since you have a .vue file (requiring the vue-loader Webpack plugin)...
You can use raw-loader to load the .txt file as a string.
Install raw-loader from NPM with:
npm i -D raw-loader
In <projectroot>/vue.config.js, configure Webpack to use raw-loader for *.txt:
module.exports = {
//...
chainWebpack: config => {
config.module
.rule('raw')
.test(/\.txt$/)
.use('raw-loader')
.loader('raw-loader')
.end()
},
}
In your component's .vue file, use import or require to load hello.txt:
<script>
import helloText from './hello.txt'; // OR: const helloText = require('./hello.txt')
export default {
//...
methods: {
getPoemList () {
console.log({ helloText });
}
}
}
</script>
<template>
<body>
<div> hello world {{variable}}</div>
</body>
</template>
<script>
var $ = require('jquery');
window.jQuery = $;
export default {
data() {
return {
variable: "",
}
},
mounted() {
methods: {
// create a vm variable pointing this
const vm = this;
function reqListener() {
// captures the local value this.responseText to vm (this vuejs) vm.variable
vm.variable = this.responseText;
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "hello.txt");
oReq.send();
}
}
}
</script>
<style> </style>

Categories

Resources