Nuxt js restart server on api folder changes - javascript

In my nuxt js application, I am trying to restart the server files which is in the api folder when a file changes.
In order to that, I've added the following to nuxt.config.js
build: {
watch: ["~/api/index.js"]
}
When I make the changes on the files in API folder server doesn't restarted automatically
I've tried this thread Watch and reload api folder in Vue Nuxt looks similar to my problem but it doesn't worked for me

As suggested here
Watch and reload api folder in Vue Nuxt
just adding
watch: ['api'],
to nuxt.config.js, at the root level, worked for me. Not under build, as you had it.
EDIT
Bizarrely, although I now see the server (and client, for some reason) being started in the console... the new code is not taken! So, that's fairly useless.
The only way to get the code changes is still to ctrl-C and restart from zero.

In my application, I use nodemon.json config
{
"verbose": true,
"ignore": ["node_modules", "dist"],
"watch": [
"app.js"
],
"ext": "js json"
}

Related

Nuxt3 Robots.txt - #nuxtjs/robots not generating robots.txt file

I'm building a Nuxt 3 project. I need my build to generate a robots.txt file, just like this package states it does -> https://github.com/nuxt-community/robots-module
After running "nuxt build" and/or "nuxt generate", the robots.txt does not appear in the output or public folders as I'd expect.
I'm definitely missing something and likely being an idiot here.. Does anyone know what I'm missing? Here's my code:
package.json
"dependencies": {
...
"#nuxtjs/robots": "^2.5.0",
}
nuxt.config.ts
target: "static",
runtimeConfig: {
NUXT_STORYBLOK_PRODUCTION_KEY: process.env.NUXT_STORYBLOK_PRODUCTION_KEY,
public: {
CDN: process.env.CDN,
NUXT_STORYBLOK_PREVIEW_KEY: process.env.NUXT_STORYBLOK_PREVIEW_KEY,
NUXT_DOMAIN_NAME: process.env.NUXT_DOMAIN_NAME,
},
},
modules: [
...
"#nuxtjs/robots",
],
robots: {
UserAgent: "*",
Disallow: "",
},
}
I just successfully installed this module on Nuxt 3, and I think there are a couple of things to note here.
The first is that I've never managed to get the module options for any module to work in Nuxt 3 the way you have shown (top-level options, according to the module docs):
modules: [
...
"#nuxtjs/robots",
],
robots: {
UserAgent: "*",
Disallow: "",
}
Have you tried the other options? You can also try using the Robots Config file, or pass the options when declaring the module (from the README.md for the repo):
export default {
modules: [
// Simple usage
'#nuxtjs/robots',
// With options
['#nuxtjs/robots', { /* module options */ }]
]
}
The other thing is that I also do not see a generated robots.txt file anywhere after running the build or dev, but if I go to '/robots.txt' in the dev or build preview, I can see the output working as intended. Have you tried visiting the path?
It looks like something the server generates when the route is visited rather than a static file generated on build by default. I think you can change that in the options, but it's not something I need so I haven't dug into it.
Hopefully, that helps somewhat!
You are using an incompatible version of nuxt robots for your project. Ensure you are using version ^3.0.0. Any versions below this are not compatible with nuxt 3.
npm install #nuxtjs/robots#3.0.0
Then ensure your nuxt.config.ts looks similar to below. As John Overstreet mentioned above the simple method appears flawed.
I created a config folder in the root directory of my project and placed my robots.txt file within it:
export default {
modules: [
['#nuxtjs/robots', { configPath: "~/config/robots.config" }]
]
}
You will also need to delete the robots.txt file from your public folder
Build/Generate your project and go to '/robots.txt'
The file is generated dynamically upon request of the above route.
With mine and John's help above I hope this helps resolve your issues :)

Fast Refresh with Next.js development mode in VS Code Remote Container/devcontainer

I can't get Next.js' Fast Refresh feature to work with a VS Code Remote Container. I can run npm run dev and see the app running on localhost on my machine, so the container works fine - only the Fast Refresh has no effect at all.
Next.js version: v11.0.1
I tried this both with Windows 10 and Ubuntu 20.04 (on WSL 2).
I already tried to use a custom webpack middleware in the next.config.js like so (see https://github.com/vercel/next.js/issues/2179#issuecomment-316568536):
module.exports = {
webpackDevMiddleware: (config) => {
// Solve compiling problem via vagrant
config.watchOptions = {
poll: 1000, // Check for changes every second
aggregateTimeout: 300, // delay before rebuilding
};
return config;
},
};
...which will trigger a recompile on code changes, but the browser does not update.
Also, the requests to "HMR" are failing:
How to reproduce:
Install the Remote Containers extension
Open any new folder
Open the command palette and type/select "Remote-Containers: Rebuild and Reopen in Container"
Type/select "Node.js"
Type/select version "16" and wait for the container to start
Go to the .devcontainer folder and open the devcontainer.json
Edit the config by adding "forwardPorts": [3002], to make the app available on your host and rebuild the container (via VS Code's command palette)
From the terminal, install Next.js, e.g.: npx create-next-app --use-npm --example with-typescript-eslint-jest my-app
Move all the files from my-app to your VS Code project root folder. This has to be done because create-next-app does not work installing in the project root folder via ., because there's already the .devcontainer folder.
Optional: Create a next.config.js and add the snippet for the Webpack dev middleware as seen above
Edit the package.json script to use a specific port: "dev": "next dev -p 3002", (or, if you use WSL 2: next dev -p 3002 -H ::)
From the terminal, start the app npm run dev
Open the browser on http://localhost:3002
The app is showing. Make changes in the code -> even a recompiled app will not show the changes in the browser. A reload of the page in the browser will show the changes though.
With Create React App, there's an advanced configuration without ejecting (called CHOKIDAR_USEPOLLING), which makes their Fast Refresh work with Remote Containers.
Earlier I created a feature request, but maybe someone already managed to make this work without huge changes in the configuration/setup?
A lot has changed between me noticing this issue and the current version of Next.js (v12.1.6).
I just tried it out again and it finally seems to work! 🥳
I'm going to change my Next.js projects to use devcontainers and maybe other stuff does not work, but at least for Fast Refresh, this topic is solved.
If you're following the steps above, the most basic setup should look like the following. It is based on the default "Node.js v16" devcontainer preconfiguration.
You don't even need to forwardPorts anymore!
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.234.0/containers/javascript-node
{
"name": "My project",
"build": {
"dockerfile": "Dockerfile",
// Update 'VARIANT' to pick a Node version: 18, 16, 14.
// Append -bullseye or -buster to pin to an OS version.
// Use -bullseye variants on local arm64/Apple Silicon.
"args": { "VARIANT": "16" }
},
"settings": {},
"extensions": [
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node"
}

How to create an express api executable

I have created a fully functioning fairly basic javaScript Node.js Express API application that I want to run as an executable in a windows environment. I am wanting to do this so I can give clients the ability to run my API on premise without exposing my source code to them.
Currently I have been using the pkg npm package which allows me to package my node.js application into an executable that will contain everything needed to run the app including node and my bundled source code.
My executable runs but my POST route is breaking with the following error:
"name": "RequestError",
"message": "Error: form-data: File or directory 'C:\\**\\myapp-api\\uploads\\1553103249524_test.wav' was not included into executable at compilation stage. Please recompile adding it as asset or script.",
"cause": {
"errno": -4058,
"code": "ENOENT",
"path": "C:\\snapshot\\myapp-api\\uploads\\test.wav",
"pkg": true
},
"error": {
"errno": -4058,
"code": "ENOENT",
"path": "C:\\snapshot\\myapp-api\\uploads\\1553103249524_test.wav",
"pkg": true
},
My POST allows clients to upload a file in a multipart form using multer.js to another external API that will return some metadata. pkg.js doesn't appear to have the means to discover files that are included after the bundling of the executable.
Is there anything I can do in my configuration for my uploaded files to be included? Is there some other utility or process that others use for creating an executable of their node.js express APIs that would better handle the issue I am having?
Any guidance would really be great.
Try adding your files under "assets" in the package.json file.
The config paragraph on the pkg website https://www.npmjs.com/package/pkg#config states:
So you must specify the files - scripts and assets - manually in pkg property of your package.json file.
"pkg": {
"scripts": "build/**/*.js",
"assets": "views/**/*"
}
You may also specify arrays of globs:
"assets": [ "assets/**/*", "images/**/*" ]
Just be sure to call pkg package.json or pkg . to make use of scripts and assets entries.
You are probably using something like this in your script (I am guessing since you didnt provide this part of the code)
app.use(express.static(__dirname+'/uploads'));
res.sendFile(path.join(__dirname+'/uploads'));
__dirname will be wrong when you pack your .exe get rid of it everywhere and replace it with ./
app.use(express.static('./uploads'));
res.sendFile(path.join('./uploads'));
Something like that. It worked for me.
Good luck!

firebase deploy of create react app exposes all js code in the source tab?

I have compiled my app via create react app: yarn build //code is minified and obfuscated as expected
I have then deployed the app via both firebase serve and firebase deploy.
my firebase.json:
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
All is deployed "almost as expected", with 2 caveats:
inside Chrome developer tools/ Sources tab, my entire js codebase is listed with no minification and or obfuscation!
my fonts are not being deployed as the media folder doesnt seem to transfer
The structure looks nothing like the build folder which contains the media... (necessary for fonts):
Am I setting something up incorrectly, deploying the wrong folder or possibly not ignoring something I should be? Exposing the entire js stack unminified and or without any obfuscation seems very "un-secure"...
Again, and as always any and all direction is greatly appreciated!
Strongly advise to refer to the create-react-app github discussion here about this matter but as a quick workaround you can add the following to your package.json scripts:
"scripts": {
...
"build": "npm run build-css && react-scripts build && yarn run delete-maps",
"delete-maps": "rm ./build/static/js/*.map && rm ./build/static/css/*.map",
...
}
This will however in the short run remove all of your source code from the Source tab in developer tools...
Prefixing GENERATE_SOURCEMAP=false to your build target works too (which obviously doesn't generate sourcemap). In package.json file.
GENERATE_SOURCEMAP=false react-scripts build

Browser sync for Angular SPA

I'm using browser sync with an Angular SPA. Serving the site looks like this:
gulp.task('serve', function() {
browserSync.init(null, {
server: {
baseDir: './',
middleware: [historyApiFallback()]
}
});
});
This works fine. The use of historyApiFallback (npm module) means browser sync doesn't freak out when going to a new URL path when all it needs to do is continue serving the index.html.
The problem I have is with watching files. I've tried this:
gulp.task('watch', function() {
watch('./src/scss/**/*.scss', function() {
runSequence('build-css', browserSync.reload);
});
});
The watch task does work because the build-css task triggers fine. Then the console logs Reloading Browsers... and just hangs. The browser never gets the CSS injection or reload. What am I doing wrong here?
Note that I'm using gulp-watch not the native gulp watch purposely.
I recommend you to use the lite-server. It is a simple customized wrapper around BrowserSync to make it easy to serve SPAs(you don't even have to configure the history api).
You can use it by simple adding an entry in the scripts object in your package.json and running the following command: npm run dev.
"scripts": {
"dev": "lite-server"
},
The module will automatically watch for changes of your files and keep then sync. So it will work with your gulp, because it will update your browser after the build-css task is executed(because the output files will change).
I am currently using it with angular 1, angular 2 and vue.js and worked fine with all.

Categories

Resources