Cannot use import statement outside a module - node.js

I'm faced with a problem with my API in Heroku. I have a Node JS API, built with Typescript and hosted in Heroku. Everything looks correct when I try to execute the local script and build the script, but when I need to run the start script, things don't work.
My configurations are:
Node: v18.12.1
NPM: v8.19.2
I have some scripts to transpile .ts files to .js files with babel
"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files",
"dev:server": "ts-node-dev -r tsconfig-paths/register --inspect --transpile-only --ignore-watch node_modules src/shared/infra/http/server.ts",
"start": "node dist/shared/infra/http/server.js"
When I execute dev:server and build script, everything runs with success, but when I run the start script, I receive this error:
enter image description here
I checked some points, like my tsconfig.json and my babel.config, but everything looks correct.
module.exports = {
presets: [
['#babel/preset-env', { targets: { node: 'current' } }],
'#babel/preset-typescript',
],
plugins: [
[
'module-resolver',
{
alias: {
'#modules': './src/modules',
'#config': './src/config',
'#shared': './src/shared',
},
},
],
'babel-plugin-transform-typescript-metadata',
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
[
'const-enum',
{
transform: 'removeConst',
},
],
],
};
Because of it, when I deploy API in Heroku, I recive this error:
enter image description here.
I don't have an idea why this occur, because about 1 month ago the API was running perfectly on Heroku production instance.
I appreciate it if anyone can help and give me some tips, about this problem.
What I tried
Check and change my npm and node versions
Check babel confgs
Add "type":"module"in my packages.json

Related

Generate stand alone js artifacts using Vite as side effect of another build

I'm using Vite (vite#3.1.8)
to build Typescript artifacts for an SPA "site" using SolidJS (solid-js#1.6.0).
here's my vite.config.ts
import { defineConfig, resolveBaseUrl } from 'vite'
import solidPlugin from 'vite-plugin-solid'
export default defineConfig({
plugins: [solidPlugin()],
server: {
port: 3000,
},
build: {
target: 'esnext',
outDir: '../htdocs',
rollupOptions: {
input: {
index: "./index.html",
dev: "./dev.html",
test: "./test.ts",
},
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`
}
},
},
});
Currently, it actually builds 2 html files (index.html and dev.html) and the artifacts needed to run those files. Its great. Couldn't be happier.
I would like to have the transpiler to also kick out test.js so that I can run it to do some sanity checking before deploying to production.
I'm hoping to do vite build, and then run node ../htdocs/assets/test.js (or something similar), and have it block the final deployment if any my sanity tests fail.
however, when I attempt to do this, I get an error when I run test.js, complaining about my use of import statements.
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
setting my package type to module in package.json doesn't fix it. changing the test file to test.mjs doesnt fix it. I'm not really sure what to try next.
What I really wish it would do is do the whole "import" as part of transpiling, and make one self-contained test.js that just runs. It seems like that is what it does when it builds index.html and dev.html, why wont it do that for my ts file?
That should work. I just tried making a new repo with your vite.config.ts, one-line index.html, dev.html, and test.ts files, and vite, vite-plugin-solid, solid-js installed. In the end I got a ../htdocs/assets/test.js file.
You might also be interested in checking out Vitest which makes testing like this easier to do, and won't accidentally end up in your deployed htdocs.
The best solution I could find was to make a separate config file for building the tests.
import { defineConfig } from 'vite'
import solidPlugin from 'vite-plugin-solid'
export default defineConfig({
plugins: [solidPlugin()],
server: {
port: 3000,
},
build: {
target: 'esnext',
outDir: '../htdocs',
lib: {
entry: "./test-runner.ts",
name: "test-runner",
fileName: "test-runner"
},
rollupOptions: {
},
},
});
and then, update my package.json to make my test script compile and run the output from that alternative vite config.
"scripts": {
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "vite build --config vite.config-tests.ts && node ../htdocs/test-runner.umd.js"
},

Reduce Loopback4 build times in development (build + restart dev server)

I am using Loopback4 to develop api in Node.
I was using the instruction given to build and watch with nodemon
It worked, but it was getting slow, like about 15 seconds in my case.
I search for other other solution and came up with idea of using Turborepo and the nodemon solution.
I wanted to know if there are better solutions or any issues with it
Gist of the solution
run build in watch mode and restart the dev server if js files in dist folder change
use Turbo repo to run these build and restart server tasks
Steps
Setup build and watch with nodemon as described in the thread
you should have something like this in the script
"scripts": {
"dev:server:watch": "nodemon server.js"
}
// watch src folder
// ignore dist
// ext only ts files
// npm start to start the dev server on any changes to the files
"nodemonConfig": {
"verbose": true,
"watch": [
"src/"
],
"ignore": [
"dist/*"
],
"ext": "ts",
"exec": "npm start"
}
Install turbo build system
yarn add turbo --dev
Update nodemon config to restart server on changes in js files in dist folder after build step
"nodemonConfig": {
"verbose": true,
"watch": [
"./dist/"
],
"ext": "js",
"exec": "yarn run start"
},
Add turbo.json
{
"pipeline": {
"dev": {
"dependsOn": ["build:watch", "dev:server:watch"]
},
"build:watch": {
"outputs": [
".dist/**"
]
},
"lint": {
"outputs": []
}
}
}
Add dev script in package.json "scripts"
"dev": "turbo run dev",
Run
yarn run dev
This seems to have reduced the build times to about 3 seconds
Can anyone confirm if this is an acceptable solution, points out any issues
Thanks

Firebase functions - compile typescript code before running emulators:start

I have a Firebase project setup with /functions directory, where all the source code is getting compiled from /src to the /dist directory.
The question is: how to configure Firebase in such way that it will run tsc command each time before starting the Local Emulator Suite? I wonder if there is a similar property to functions.predeploy in firebase.json config, but for the Local Emulator Suite:
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"functions": {
"predeploy": [
"npm --prefix functions run build"
],
// something like this:
"preemulator": [
"npm --prefix functions run build"
]
}
}
Here is a build script from package.json:
"scripts": {
// ...
"build": "./node_modules/.bin/tsc",
}

Use flag `--experimental-worker` with babel-node

babel-node --experimental-worker app.js
Using this command for starting my project in development mode. Output is:
error: unknown option--experimental-worker'
config .babelrc:
{ "presets": [ ["env", { "targets": { "node": "current" } }], "stage-0", "flow" ], "plugins": [ "transform-decorators-legacy", "transform-flow-strip-types" ] }
This flag is needed to use worker threads. Using babel 6.26
I just ran into this today and replied to the issue on GitHub here. I've pasted my fix below:
I was using Nodemon, and it turns out that there's an option to
include environment variables as NODE_OPTIONS in the nodemon.json
file. This did the trick for me:
{
"watch": ["server"],
"ext": "js",
"env": {
"NODE_OPTIONS": "--experimental-worker"
},
"exec": "babel-node server/server.js"
}
How to integrate Nodemon + worker_threads into a normal NodeJS app:
Set up Nodemon
Add a nodemon.json file to the root folder (example here)
Add this to nodemon.json:
"env": {
"NODE_OPTIONS": "--experimental-worker"
}
If you're setting up Nodemon for the first time, I found
this tutorial very helpful.
The idea is to split your command into two phases:
Phase 1:
babel app.js --out-file app-compiled.js
And phase 2:
node --experimental-worker app-compiled.js
In npm scripts you can then combine the two:
"scripts": {
"pre-build": "babel ./app.js --out-file ./app-compiled.js",
"serve": "yarn pre-build && node --experimental-worker ./app-compiled.js"
}
It not actually for me already. I am refused to use nodemon and run my code with command
node --experimental-worker -r babel-register $NODE_DEBUG_OPTION app.js
It`s help me use exeprimental workers with babel, but with nodemon - not

Webpack not updating on Heroku rebuild

I have a Node app which builds React with Webpack and is hosted on Heroku. Whenever I push a newer version to Heroku master, the React files do not update. I have now pushed several newer versions but the React files in webpack:// will not update and remain the originals from when I first deployed the app.
Here is my webpack.config.js file:
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
main: `${__dirname}/src/app.js`
},
output: {
path: __dirname,
filename: './public/bundle.js'
},
module: {
loaders: [{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}]
},
devtool: 'cheap-module-eval-source-map'
};
My package.json includes "heroku-postinstall": "webpack -p -w --config ./webpack.config.js --progress".
I also faced similar issue.
(Just make sure that your webpack config file is correct and does not have any errors while running the webpack build locally)
I modified my post-install script in following way inside my package.json
"scripts": {
"clean": "rimraf public/bundle.*",
"build": "cross-env NODE_ENV=production webpack --config ./webpack.prod.config.js --progress --colors",
"postinstall": "npm run clean && npm run build",
}
When I push my changes to heroku "postinstall" gets called and it perform to task one after another
clean old build files
generate new build
In this way old files gets deleted from cache.
but there are are few dependencies which you need to install
rimraf
npm install --save rimraf
You can choose any other alternative to "rimraf" as well.

Resources