Please tell me how to set up the preact-render-to-string on the express.
https://github.com/preactjs/preact-render-to-string#render-jsx--preact--whatever-via-express
https://expressjs.com/en/starter/installing.html
I built it reading the above links. The source code is on there, but I'm not used to node
I don't know how to execute it(Or I don't know if I'm failing to build the environment.).
I believe my installation procedure can be found in package.json(dependencies and devDependencies). So, below is my package.json.
My package.json:
{
"name": "y",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"preact": "^10.5.14",
"preact-render-to-string": "^5.1.19"
}
}
My app.js (Same as Document):
I didn't know what to do with the file name, so I used app.js.
import express from 'express';
import { h } from 'preact';
import render from 'preact-render-to-string';
/** #jsx h */
// silly example component:
const Fox = ({ name }) => (
<div class="fox">
<h5>{ name }</h5>
<p>This page is all about {name}.</p>
</div>
);
// basic HTTP server via express:
const app = express();
app.listen(8080);
// on each request, render and return a component:
app.get('/:fox', (req, res) => {
let html = render(<Fox name={req.params.fox} />);
// send it back wrapped up as an HTML5 document:
res.send(`<!DOCTYPE html><html><body>${html}</body></html>`);
});
Run and Error:
$ node app.js
src/pr/ex/app.js:1
import express from 'express';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
I think I am running it wrong or failed to build the environment, what can I do to make it run successfully?
node is installed with nodebrew. The current status is as follows.
$ nodebrew list
v16.6.2
current: v16.6.2
Edit:
I tried the answer.
add the top-level "type" field with a value of "module"
The error SyntaxError: Cannot use import statement outside a module is gone and different error occurred.
$ node app.js
file:///src/pr/ex/app.js:8
<div class="fox">
^
SyntaxError: Unexpected token '<'
at Loader.moduleStrategy (node:internal/modules/esm/translators:146:18)
at async link (node:internal/modules/esm/module_job:67:21)
Since I am using preact (I must be using htm internally), it is odd that Unexpected token '<' would be an error.
package.json after editing:
{
"name": "y",
"version": "1.0.0",
"type": "module",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"preact": "^10.5.14",
"preact-render-to-string": "^5.1.19"
}
}
Possible solutions:
Use require:
const express = require('express')
const { h } = require('preact')
Save your app.js file as a .mjs file (Node13+ only)
Add { type: 'module' } in your package.json
Related
I am using the firebase-admin library in my node application.
My index.js is empty, with the exception of the require statement for firebase-admin...
var admin = require('firebase-admin');
The exception being thrown from the require statement occurs at following line in firebase-admin/lib/default-namespace.js
const firebase_namespace_1 = require("./app/firebase-namespace");
The exception message is as follows...
Exception has occurred: SyntaxError: Unexpected token ?
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:686:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:734:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:659:17)
at require (internal/modules/cjs/helpers.js:22:18)
My package.json is as follows...
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"firebase-admin": "^11.0.1"
}
}
I am running node version v16.16.0
Before adding
"type": "module", in package.json it used to give the following error
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Work\ts-api\node_modules\node-fetch\src\index.js
require() of ES modules is not supported.
require() of C:\Work\ts-api\node_modules\node-fetch\src\index.js from C:\Work\ts-api\src\app.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Work\ts-api\node_modules\node-fetch\package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Work\ts-api\src\app.ts:3:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Module.m._compile (C:\Work\ts-api\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (C:\Work\ts-api\node_modules\ts-node\src\index.ts:1374:12) {
code: 'ERR_REQUIRE_ESM'
}
but then I added "type": "module", in package.json
and it started to giving me the error which I mentioned in title
./src/app.ts
import express,{Application, Request, Response, NextFunction} from 'express';
import fetch from 'node-fetch';
const app:Application = express();
app.get("/",(req:Request, res:Response)=>{
res.send("Hello world");
})
app.get("/api",async (req:Request, res:Response)=>{
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
const data = await response.json();
console.log(data);
});
app.listen(3000,()=>{
"Server is started at Port No. 3000"
});
package.json
{
"name": "ts-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"build": "tsc -p ."
},
"keywords": [],
"type": "module",
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^17.0.7",
"nodemon": "^2.0.15",
"ts-node": "^10.4.0",
"typescript": "^4.5.4"
},
"dependencies": {
"express": "^4.17.2",
"node-fetch": "^3.1.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
I think you should use axios instead of node-fetch because node-fetch doesn't support commonjs ES modules, also you can remove "type": "module"
app.ts
import express,{Application, Request, Response, NextFunction} from 'express';
import axios from 'axios';
const app:Application = express();
app.get("/",(req:Request, res:Response)=>{
res.send("Hello world");
})
app.get("/api",async (req:Request, res:Response)=>{
const { data } = await axios.post('https://httpbin.org/post','a=1');
console.log(data);
});
app.listen(3000,()=>{
"Server is started at Port No. 3000"
});
I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.
What do I need to change to get import to work?
I have 3 simple files in the same directory.
package.json
main.js
Utility.js
package.json
{
"name": "node_template",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Utility.js
'use strict';
class Utility {
constructor() {
}
}
export { Utility };
main.js
"use strict";
(async ()=>{
import { Utility } from './Utility.js';
var utility = new Utility();
console.log( "Main" );
})();
When I run "node main.js" I get the following error:
node -v
v16.0.0
node main.js
main.js:4
import { Utility } from './Utility.js';
^
SyntaxError: Unexpected token '{'
←[90m at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m at async link (node:internal/modules/esm/module_job:64:21)←[39m
main.js
(async () => {
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();
Note:
The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.
Links:
https://v8.dev/features/dynamic-import
https://flaviocopes.com/javascript-dynamic-imports/
I have a file index.ts:
import { app, BrowserWindow } from 'electron'
let win
app.on('ready', () => {
win = new BrowserWindow({
minHeight: 640,
minWidth: 480,
frame:false
})
win.loadFile('index.html')
})
If I try to run with: npm start, I got an error:
import { app, BrowserWindow } from 'electron'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1051:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
at Module.load (internal/modules/cjs/loader.js:981:32)
at Module._load (internal/modules/cjs/loader.js:881:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at loadApplicationPackage (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:109:16)
at Object.<anonymous> (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:155:9)
at Module._compile (internal/modules/cjs/loader.js:1145:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
My package.json:
{
"name": "electron-app",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"dependencies": {
"electron": "^10.1.2"
},
"devDependencies": {},
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
How I can solve it?
It looks like you are trying to use TypeScript with Electron. Electron has types available, however it doesn't directly support executing TypeScript right out of the box. You will need to perform some additional steps to get things working. This goes a bit out of scope of an answer, and would need to be more of a tutorial or example, so I'll provide you with an example from GitHub.
You can view an example of getting started with TypeScript and Electron Here.
Electron runs through node.js and node.js is behind and uses commonjs import syntax.
To import we do:
const {app} = require("electron");
// equivalent to
//import {app} from 'electron' <- don't use in electron
to export we do:
module.exports = app;
// equivalent to
//export default app; <- don't use in electron
I'm using Heroku and I get this error..
2016-10-10T03:34:11.188366+00:00 app[web.1]: Error: Cannot find module 'module1.js'
2016-10-10T03:34:11.188369+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:339:15)
2016-10-10T03:34:11.188370+00:00 app[web.1]: at Function.Module._load (module.js:290:25)
2016-10-10T03:34:11.188371+00:00 app[web.1]: at Module.require (module.js:367:17)
2016-10-10T03:34:11.188371+00:00 app[web.1]: at require (internal/module.js:20:19)
2016-10-10T03:34:11.188372+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:42:15)
2016-10-10T03:34:11.188373+00:00 app[web.1]: at Module._compile (module.js:413:34)
2016-10-10T03:34:11.188374+00:00 app[web.1]: at Object.Module._extensions..js (module.js:422:10)
2016-10-10T03:34:11.188374+00:00 app[web.1]: at Module.load (module.js:357:32)
2016-10-10T03:34:11.188375+00:00 app[web.1]: at Function.Module._load (module.js:314:12)
2016-10-10T03:34:11.188375+00:00 app[web.1]: at Function.Module.runMain (module.js:447:10)
app.js
/**CUSTOM_MODULES**/
var module1 = require('module1.js');
/**MODULES_END**/
module1.js
function module1(){
//My code
}
module.exports = module1;
module1.js is in the same directory as my app.js.
I have tried countless things but nothing seems to work.
I have tried:
var module1 = require('module1.js');
var module1 = require('./module1.js');
var module1 = require('../module1.js');
var module1 = require('module1');
package.json : app.js
{
"name": "nano-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"express": "^4.14.0",
"mysql": "^2.11.1",
"socket.io": "^1.4.8",
"module1": "0.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC"
}
package.json : module1
{
"name": "module1",
"version": "0.0.0",
"description": "get something",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": {
"name": "sergey"
},
"license": "BSD-2-Clause",
"readme": "ERROR: No README data found!",
"_id": "module1#0.0.0",
"dist": {
"shasum": "dc9b96f8a43b596bf735da4d2004ba410429bde0",
"tarball": "https://registry.npmjs.org/module1/-/module1-0.0.0.tgz"
},
"_from": "module1#latest",
"_npmVersion": "1.3.11",
"_npmUser": {
"name": "sergey-user",
"email": "aaa#mail.ru"
},
"maintainers": [
{
"name": "sergey-user",
"email": "aaa#mail.ru"
}
],
"directories": {},
"_shasum": "dc9b96f8a43b596bf735da4d2004ba410429bde0",
"_resolved": "https://registry.npmjs.org/module1/-/module1-0.0.0.tgz"
}
directory
_server
.git
node_modules
.bin
express
module1
index.js
package.json
mysql
node-mysql
node-uuid
socket.io
package.json
server.js
Try var module1 = require('./module1');
Adding your module as a dependency to your application would resolve this issue. To achieve that try the below command.
npm install module1 --save
Hope this helps!
install npm -g and try again afterwords.
In my case, after trying everything without any success, updating node helped (v10.3.1 -> v12.13.1).