I have an existing Node.js (Node only, no Typescript) application with the following files (generated by Visual Studio Node template):
In file app.js:
var express = require("express");
var app = express();
...
module.exports = app;
In file socket.js:
module.exports = function (server,app) {
// ....
}
In file www:
var app = require("../app");
var server = app.listen(app.get(8081), function() {
});
var sockets = require("../routes/sockets")(server, app);
I am no migrating it to Typescript. How do I convert the above export/require to the equivalent in Typescript?
Where can I find the proper specifications of the import and export keywords? I am unable to find documentation of what they mean and do exactly. I do see many examples of some permutations of their usage.
To ensure that your import statements will be transpiled into require(), you need to specify that you want to use commonjs modules during the TypeScript compilation. Here's an example of tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "build",
"target": "es5"
}
}
Here's an example of the Node/Express server in TypeScript:
import * as express from "express";
const app = express();
app.get('/products', (req, res) => res.send('Got a request for products'));
const server = app.listen(8000, "localhost", () => {
const {address, port} = server.address();
console.log('Listening on %s %s', address, port);
});
Related
After I migrated Cypress to version 10, Cucumber preprocessor stopped to work. I have found some solutions that I implemented and I also installed the latest #badeball/cypress-cucumber-preprocessor.
Now I am stuck how to set up the cypress.config.js file, as the original plugins folder is deprecated.
In old index.js under plugin folder I had:
const cucumber = require("cypress-cucumber-preprocessor").default;
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on("file:preprocessor", cucumber());
...
Now the plugin setup should be in cypress-config.js:
e2e: {
baseUrl: 'http://localhost:4200',
specPattern: 'cypress/e2e/features',
setupNodeEvents(on, config) {
const addCucumberPreprocessorPlugin =
require('#badeball/cypress-cucumber-preprocessor').addCucumberPreprocessorPlugin;
on('file:preprocessor', addCucumberPreprocessorPlugin(on, config));
}
},
but now I have an error in on('file:preprocessor', addCucumberPreprocessorPlugin()); that addCucumberPreprocessorPlugin is not a function. I know it is not, but how to correctly configure this section for cucumber? I did not find any info about this.
If I just remove the on('file:preprocessor', addCucumberPreprocessorPlugin(on, config));, after I execute the feature test file, I have this error:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
The pattern I'm using is
import { defineConfig } from "cypress";
const preprocessor = require("#badeball/cypress-cucumber-preprocessor");
async function setupNodeEvents(on, config) {
await preprocessor.addCucumberPreprocessorPlugin(on, config);
// webpack config goes here if required
return config;
}
module.exports = defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});
You may need some webpack config as well, the repository has some examples here
Here's another config that's working for me
const { defineConfig } = require("cypress");
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const preprocessor = require("#badeball/cypress-cucumber-preprocessor");
const createEsbuildPlugin = require("#badeball/cypress-cucumber-preprocessor/esbuild");
async function setupNodeEvents(on, config) {
await preprocessor.addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin.default(config)],
})
);
// Make sure to return the config object as it might have been modified by the plugin.
return config;
}
module.exports = defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});
You can try this:
Install two dependencies #bahmutov/cypress-esbuild-preprocessor and #esbuild-plugins/node-modules-polyfill using:
npm install -D #bahmutov/cypress-esbuild-preprocessor
npm install -D #esbuild-plugins/node-modules-polyfill
In your cypress/plugin/index.js, remove:
const cucumber = require('cypress-cucumber-preprocessor').default
module.exports = (on, config) => {
on('file:preprocessor', cucumber()) //For cypress cucumber preprocessor
}
and Add,
//For Cucumber Integration
const createEsbuildPlugin =
require('#badeball/cypress-cucumber-preprocessor/esbuild').createEsbuildPlugin
const createBundler = require('#bahmutov/cypress-esbuild-preprocessor')
const nodePolyfills =
require('#esbuild-plugins/node-modules-polyfill').NodeModulesPolyfillPlugin
const addCucumberPreprocessorPlugin =
require('#badeball/cypress-cucumber-preprocessor').addCucumberPreprocessorPlugin
module.exports = async (on, config) => {
await addCucumberPreprocessorPlugin(on, config) // to allow json to be produced
// To use esBuild for the bundler when preprocessing
on(
'file:preprocessor',
createBundler({
plugins: [nodePolyfills(), createEsbuildPlugin(config)],
})
)
return config
}
In your package.json, add:
"cypress-cucumber-preprocessor": {
"stepDefinitions": "cypress/e2e/path-to-step-definition/**/*.{js,ts}"
}
Next, in the step definition file replace import { Given, When, Then } from ‘cypress-cucumber-preprocessor/steps’
with
import { Given, When, Then, And } from “#badeball/cypress-cucumber-preprocessor”.
For your feature files to be recognised by the cypress test runner, update the specPattern in cypress.config.js file to [“**/*.feature”, “cypress/e2e/**/*.cy.{js,jsx,ts,tsx}”].
In case anyone else gets to this solution but is using webpack and typescript I had to make a few tweaks to our existing tsconfig.json:
"esModuleInterop": false,
"noEmit": false,
Aside from that the Cypress 10 conversion tool and the examples from the #badeball/cypress-cucumber-preproccesor docs for webpack/ts were all I needed.
I need help in running my Vue spa in the same domain as my laravel app , when running "npm run serve" in terminal I think it's working but when I go to the browser it's refusing connection. I haven't done the backend which I will use sanctum for handling API. Has anybody here have the same project working on like me? love to make conversations to solve this.
Thanks in advance
here is the vue.config.js file
const path = require('path')
const webpack = require('webpack')
const createThemeColorReplacerPlugin = require('./config/plugin.config')
function resolve (dir) {
return path.join(__dirname, dir)
}
/**
* check production or preview(pro.loacg.com only)
* #returns {boolean}
*/
function isProd () {
return process.env.NODE_ENV === 'production'
}
const assetsCDN = {
css: [],
// https://unpkg.com/browse/vue#2.6.10/
js: [
'//cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.min.js',
'//cdn.jsdelivr.net/npm/vue-router#3.1.3/dist/vue-router.min.js',
'//cdn.jsdelivr.net/npm/vuex#3.1.1/dist/vuex.min.js',
'//cdn.jsdelivr.net/npm/axios#0.19.0/dist/axios.min.js'
]
}
// webpack build externals
const prodExternals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios'
}
// vue.config.js
const vueConfig = {
configureWebpack: {
// webpack plugins
plugins: [
// Ignore all locale files of moment.js
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// if prod is on, add externals
externals: isProd() ? prodExternals : {}
},
chainWebpack: (config) => {
config.resolve.alias
.set('#$', resolve('src'))
const svgRule = config.module.rule('svg')
svgRule.uses.clear()
svgRule
.oneOf('inline')
.resourceQuery(/inline/)
.use('vue-svg-icon-loader')
.loader('vue-svg-icon-loader')
.end()
.end()
.oneOf('external')
.use('file-loader')
.loader('file-loader')
.options({
name: 'assets/[name].[hash:8].[ext]'
})
// if prod is on
// assets require on cdn
if (isProd()) {
config.plugin('html').tap(args => {
args[0].cdn = assetsCDN
return args
})
}
},
css: {
loaderOptions: {
less: {
modifyVars: {
// less vars,customize ant design theme
'primary-color': '#00B4E4',
// 'link-color': '#F5222D',
'border-radius-base': '4px'
},
javascriptEnabled: true
}
}
},
}
if (process.env.VUE_APP_PREVIEW === 'true') {
vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}
module.exports = vueConfig
module.exports = {
devServer: {
host: 'app.paymate-ui.test'
}
}
If I understand you correctly, you want to use Laravel and Vue.js together in the same application folder?
Should be pretty easy then.
First off, build your application with Vue scaffolding for the frontend.
Then, make a route that redirects everything to a single controller method that returns a spa view. (Or use a closure)
In this view, include your app.js as an asset and include the main Vue component (something like <app></app>).
Then build your Vue app. All requests will now be forwarded to the spa view, which includes your app.js, which should bootstrap Vue.
I've checked the logs and this is what it says:
Here is my app.js file (at the root level):
// Importing frameworks, libraries, routes, and JSON parser
const express = require('express');
const mongoose = require('mongoose');
const rewards = require('./routes/api/rewards');
const bodyParser = require('body-parser');
const path = require('path');
// Loading static build folder for production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('frontend/build'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
})
}
// Create a new Express server
const app = express();
// Setup middleware for body parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Import MongoDB key
const db = require('./config/keys').mongoURI;
// Connect to MongoDB using Mongoose
mongoose
.connect(db, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB successfully'))
.catch(err => console.log(err));
// Create basic express routing
app.use('/api/rewards', rewards);
// Determining which port to run on
// Deploying on Heroku requires the server to be on process.env.PORT
const port = process.env.PORT || 5000;
// Start a socket and listen for connections on the path
// Display a success message when server is running correctly
app.listen(port, () => console.log(`Server is running on port ${port}`));
Any pointers/tips on what this error message is saying exactly? My best guess is that it has something to with one of my routes but I'm not too sure...
You are making your app variable below your if of production check to serve react build.
please move line
const app = express();
above your if check.
correct app.js would be:
// Importing frameworks, libraries, routes, and JSON parser
const express = require('express');
const mongoose = require('mongoose');
const rewards = require('./routes/api/rewards');
const bodyParser = require('body-parser');
const path = require('path');
// Create a new Express server
const app = express();
// Loading static build folder for production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('frontend/build'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
})
}
// Setup middleware for body parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Import MongoDB key
const db = require('./config/keys').mongoURI;
// Connect to MongoDB using Mongoose
mongoose
.connect(db, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB successfully'))
.catch(err => console.log(err));
// Create basic express routing
app.use('/api/rewards', rewards);
// Determining which port to run on
// Deploying on Heroku requires the server to be on process.env.PORT
const port = process.env.PORT || 5000;
// Start a socket and listen for connections on the path
// Display a success message when server is running correctly
app.listen(port, () => console.log(`Server is running on port ${port}`));
I deployed my 1st Nuxt.js app to Heroku...Everything went smooth but when I opened the app I realised that every .vue file/component has TailwindCSS styles up untill SM breakpoint. Mobile view is fine, but anything bigger than SM breakpoint is not apllied. I also used Purgecss to remove unused styles but not sure if that can cause the problems... Any ideas on how to fix this?
I fixed my problem just by finding this https://github.com/nuxt/nuxt.js/issues/2262
I created modules folder and added import-tailwind-config.js with the code:
module.exports = function () {
const tailwindConfig = require('#nuxtjs/tailwindcss')
this.options.env.tailwind = tailwindConfig
}
And inside nuxt.config.js, outside of module.exports I added
const PurgecssPlugin = require('purgecss-webpack-plugin')
const glob = require('glob-all')
const path = require('path')
class TailwindExtractor {
static extract (content) {
return content.match(/[A-z0-9-:/]+/g) || []
}
}
As well as this code inside of module.exports
build: {
extend (config, ctx) {
config.plugins.push(
new PurgecssPlugin({
whitelist: ['html', 'body'],
paths: glob.sync([
path.join(__dirname, 'components/**/*.vue'),
path.join(__dirname, 'layouts/**/*.vue'),
path.join(__dirname, 'pages/**/*.vue'),
path.join(__dirname, 'plugins/**/*.vue')
]),
extractors: [{
extractor: TailwindExtractor,
extensions: ['html', 'js', 'vue']
}]
})
)
}
}
modules: [
'~modules/import-tailwind-config'
]
I want to use socket.io in my Nuxtjs. Is it possible?
I tried this tutorial but I am getting the following error:
These dependencies were not found:
* fs in ./node_modules/socket.io/lib/index.js
* uws in ./node_modules/engine.io/lib/server.js
The better way to play with Nuxt.js + Socket.io is to follow this official example from core-team: https://github.com/nuxt/nuxt.js/tree/dev/examples/with-sockets
Updated answer with linked example on GitHub
I would suggest to use the nuxt-socket-io module. It is really easy to set up and has a nice documentation.
I built this litte demo example and I will list the steps that I took to build it (this is even a bit more thorough than the Setup section of the npm package):
Add nuxt-socket-io dependency to your project:
yarn add nuxt-socket-io # or npm install nuxt-socket-io
(If you already have a socket.io server you can skip this part)
Add following line to your nuxt.config.js file: serverMiddleware: [ "~/serverMiddleware/socket-io-server.js" ] (Please do not mix up serverMiddleware with middleware, this are two different things)
Then, create the file ./serverMiddleware/socket-io-server.js where you can implement your socket.io server.
// This file is executed once when the server is started
// Setup a socket.io server on port 3001 that has CORS disabled
// (do not set this to port 3000 as port 3000 is where
// the nuxt dev server serves your nuxt application)
const io = require("socket.io")(3001, {
cors: {
// No CORS at all
origin: '*',
}
});
var i = 0;
// Broadcast "tick" event every second
// Or do whatever you want with io ;)
setInterval(() => {
i++;
io.emit("tick", i);
}, 1000);
// Since we are a serverMiddleware, we have to return a handler,
// even if this it does nothing
export default function (req, res, next) {
next()
}
(If you already have Vuex set up, you can skip this)
Add following empty Vuex store, i.e., create the file ./store/index.js, since the module needs Vuex set up.
export const state = () => ({})
Add nuxt-socket-io to the modules section of nuxt.config.js, this will enable socket-io client:
{
modules: [
'nuxt-socket-io',
],
// socket.io configuration
io: {
// we could have multiple sockets that we identify with names
// one of these sockets may have set "default" to true
sockets: [{
default: true, // make this the default socket
name: 'main', // give it a name that we can later use to choose this socket in the .vue file
url: 'http://localhost:3001' // URL wherever your socket IO server runs
}]
},
}
Use it in your components:
{
data() {
return {
latestTickId: 0,
};
},
mounted() {
const vm = this;
// use "main" socket defined in nuxt.config.js
vm.socket = this.$nuxtSocket({
name: "main" // select "main" socket from nuxt.config.js - we could also skip this because "main" is the default socket
});
vm.socket.on("tick", (tickId) => {
vm.latestTickId = tickId;
});
},
}
Run it with npm run dev and enjoy your tick events :)
Nuxt + socket.io
For me worked:
Create project as nodejs app (not static page);
Install socket.io npm i socket.io;
Add serverMiddleware section to nuxt.config.js:
export default {
...,
serverMiddleware: [
{path: '/ws', handler: '~/api/srv.js'},
],
}
Create middleware /app/srv.js:
const app = require('express')()
const socket = require('socket.io')
let server = null
let io = null
app.all('/init', (req, res) => {
if (!server) {
server = res.connection.server
io = socket(server)
io.on('connection', function (socket) {
console.log('Made socket connection');
socket.on('msg', msg => {
console.log('Recived: ' + msg)
setTimeout(() => {
socket.emit('msg', `Response to: ${msg}`)
}, 1000)
})
socket.on('disconnect', () => console.log('disconnected'))
})
}
res.json({ msg: 'server is set' })
})
module.exports = app
Socket.io needs server which is not created in middleware, that's why is taken from firest request to app from res.connection.server.
Create page pages/index.vue:
<template>
<div class="container">
<input v-model="msg">
<button #click="socket.emit('msg', msg)">send</button>
<br/>
<textarea v-model="resps"></textarea>
</div>
</template>
<script>
export default {
head: {
script: [
{src: 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js'},
],
},
data () {
return {
socket: null,
msg: 'wwJd',
resps: '',
}
},
mounted () {
this.$axios.$get('/ws/init')
.then(resp => {
this.socket = io()
this.socket.on('msg', msg => this.resps += `${msg}\n`)
})
},
}
</script>
Run it npm run dev;
Modify and enjoy :-)