Unknown file extension ".ts" in ./src/app.ts - javascript

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"
});

Related

unable to use babel to run file

I'm trying to get more familiar with modern javascript and am following a tutorial. Early setup includes running a file from another file. I have a server.js file with a simple 'import './config'; command. As a test that repo setup is correct, I should be able to run 'babel server.js'. But I keep returning the error shown below. How do I troubleshoot so that I can successfully run babel commands?
myName#SE-C02YNKJ9LVCF in ~/Linkedin_Learning/modern_javascript_app_example (main) > babel src/server.js
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '#babel/plugin-proposal-class' imported from /Users/myName/Linkedin_Learning/modern_javascript_app_example/babel-virtual-resolve-base.js
at new NodeError (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:2795:5)
at packageResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3451:9)
at moduleResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3485:18)
at defaultResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3524:13)
at /usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3547:14
at Generator.next (<anonymous>)
at asyncGeneratorStep (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:63:103)
at _next (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:65:194)
at /usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:65:364
at new Promise (<anonymous>) {
code: 'ERR_MODULE_NOT_FOUND'
}
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '#babel/plugin-proposal-class' imported from /Users/myName/Linkedin_Learning/modern_javascript_app_example/babel-virtual-resolve-base.js
at new NodeError (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:2795:5)
at packageResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3451:9)
at moduleResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3485:18)
at defaultResolve (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3524:13)
at /usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:3547:14
at Generator.next (<anonymous>)
at asyncGeneratorStep (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:63:103)
at _next (/usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:65:194)
at /usr/local/lib/node_modules/#babel/cli/node_modules/#babel/core/lib/vendor/import-meta-resolve.js:65:364
at new Promise (<anonymous>) {
code: 'ERR_MODULE_NOT_FOUND'
Things I've tried so far
as per tutorial, tried updating my bash_profile w/ 'export PATH=$PATH:./node_modules/.bin'
tried setting it in global PATH variable
setting all devDependencies in package.json file that mention #babel to consistent version.
After updating package.json file, new error is below:
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/robertgorowsky/Linkedin_Learning/modern_javascript_app_example/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///Users/myName/Linkedin_Learning/modern_javascript_app_example/babel.config.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:541:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
When I run babel --version, it returns '7.19.3 (#babel/core 7.19.3)' matching package.json file.
contents of files:
content.js
console.log('config test')
server.js
import './config';
package.json
{
"name": "modern_javascript_app_example",
"version": "1.0.0",
"description": "Learning fullstack JavaScript Dev with MongoDB, Node.js, React.js",
"main": "index.js",
"type": "module", //added this line after first answer
"scripts": {
"start": "nodemon --exec babel-node server.js --ignore public/",
"dev": "webpack -wd"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rgorowsky/modern_javascript_app_example.git"
},
"author": "",
"license": "GPL-3.0",
"bugs": {
"url": "https://github.com/rgorowsky/modern_javascript_app_example/issues"
},
"homepage": "https://github.com/rgorowsky/modern_javascript_app_example#readme",
"dependencies": {
"express": "^4.18.1",
"mongodb": "^4.10.0",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/node": "^7.19.1",
"#babel/core": "^7.19.3",
"#babel/plugin-proposal-class-properties": "^7.18.6",
"#babel/preset-env": "^7.19.3",
"#babel/preset-react": "^7.18.6",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.5",
"eslint": "^8.23.1",
"eslint-plugin-react": "^7.31.8",
"nodemon": "^2.0.20",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('public'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /|.js$/,
exclude: /.node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
};
babel.config.js
module.exports = {
presets: ['#babel/react', '#babel/env'],
plugins: ['#babel/plugin-proposal-class-properties'],
};
A picture of my repo file structure for reference:
please do the following step
add "type": "module" in package.json
{
"name": "modern_javascript_app_example",
"version": "1.0.0",
"description": "Learning ...",
"main": "index.js",
"type": "module",
"scripts": {
and use import './content.js'; not import './config'; in serer.js file

return old(m, filename); Error [ERR_REQUIRE_ESM]: require() of ES Module

i'm trying to do an integration with the unsplash api but i'm getting,
when I try to run the script by ts-node like:
ts-node unsplash.ts
there is error for:
C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\USER\Desktop\tindin\node_modules\node-fetch\src\index.js from C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts not supported.
Instead change the require of index.js in C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts to a dynamic import() which is available in all CommonJS modules.
at Object.require.extensions.<computed> [as .js] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729:20)
at Object.<anonymous> (C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts:23:30)
at Module.m._compile (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:735:29)
at Object.require.extensions.<computed> [as .ts] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:737:16)
at main (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:238:16)
at Object.<anonymous> (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:351:5) {
code: 'ERR_REQUIRE_ESM'
}
my code
import { createApi } from 'unsplash-js';
import * as nodeFetch from 'node-fetch'
const unsplash = createApi({
accessKey: 'MY_ACCESS_KEY',
fetch: nodeFetch.default as unknown as typeof fetch,
});
i'm following the reference of the unsplash documentation itself
link : https://github.com/unsplash/unsplash-js
my package.json
{
"name": "typescript",
"version": "1.0.0",
"main": "server.js",
"license": "MIT",
"scripts": {
"dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
"lint": "eslint . --ext .ts",
"lint-fix": "eslint . --ext .ts --fix"
},
"devDependencies": {
"#types/node": "^17.0.8",
"#typescript-eslint/eslint-plugin": "^5.9.0",
"#typescript-eslint/parser": "^5.9.0",
"eslint": "^8.6.0",
"ts-node-dev": "^1.1.8",
"tsconfig-paths": "^3.12.0",
"typescript": "^4.5.4"
},
"dependencies": {
"node-fetch": "^3.1.1",
"unsplash-js": "^7.0.15"
}
}
my tsconfig.json
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"allowJs": true, /* Allow javascript files to be compiled. */
"outDir": "./build", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": ".", /* Base directory to resolve non-absolute module names. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"resolveJsonModule": true, /* Include modules imported with '.json' extension */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
},
"exclude": [
"node_modules",
"build"
],
"include": [
"src/**/*"
]
}
I add "type": "module" in package.json file.
{
"name": "typescript",
"version": "1.0.0",
"type": "module",
...
}
I get this error
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts
at new NodeError (node:internal/errors:371:5)
at Object.file: (node:internal/modules/esm/get_format:72:15)
at defaultGetFormat (node:internal/modules/esm/get_format:85:38)
at defaultLoad (node:internal/modules/esm/load:13:42)
at ESMLoader.load (node:internal/modules/esm/loader:303:26)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:230:58)
at new ModuleJob (node:internal/modules/esm/module_job:63:26)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:244:11)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

How to set up the preact-render-to-string on the express

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

typescript throws configure not a function error with dotenv and jest

I am trying to use dotenv and jest together, and run into an error immediately.
A single test file, tests/authenticationt.test.ts with only
require('dotenv').configure();
is sufficient to cause this error (it throws this regardless of the presence of tests):
PS C:\Users\rj\code\BGA.ts> npm run test
Debugger attached.
> # test C:\Users\rj\code\BGA.ts
> jest
Debugger attached.
FAIL tests/authentication.test.ts
● Test suite failed to run
TypeError: require(...).configure is not a function
> 1 | require('dotenv').configure();
| ^
2 |
at Object.<anonymous> (tests/authentication.test.ts:1:31)
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
modulePaths: [
"."
],
};
package.json
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"#types/jest": "^26.0.23",
"dotenv": "^10.0.0",
"jest": "^27.0.4",
"ts-jest": "^27.0.3",
"typescript": "^4.3.2"
},
"dependencies": {
"#types/puppeteer": "^5.4.3"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"strictNullChecks": true,
"outDir": "build",
"lib": [
"es2017",
"DOM"
],
},
"include": ["src/**/*"]
}
Additional details
I have not been able to find a stackoverflow question that matches this error; however, this is a basic setup question. This is on a Windows 10 machine, and I'm triggering the tests via powershell. dotenv works fine with my other typescript files (i.e. this is only a problem with jest).
try require('dotenv').config()

TypeScript cannot find namespace

I am trying to create a web game using webGL, TypeScript and node.
I have a file structure that currently looks like this
> node_modules
> src
engine.ts
webgl.ts
index.ts
index.html
package.json
engine.ts looks like this:
namespace EngineSpace {
export class Engine {
// ....
}
}
and webgl.js:
namespace EngineSpace {
export class WebGLUtil {
// ....
}
}
and index.js
window.onload = function() {
let engine = new EngineSpace.Engine();
engine.start();
}
However when I run npm start, I get that src/index.ts:5:22 - error TS2304: Cannot find name 'EngineSpace'..
I am not sure why it cannot resolve this namespace. Given that I am trying to create a game, how should I have this set up / what would be best practices?
below is the package.json: file
{
"name": "typescript-engine",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npm run build:live",
"build": "tsc -p .",
"build:live": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"#types/node": "^12.11.1",
"nodemon": "^1.19.4",
"ts-node": "^8.4.1",
"typescript": "^3.6.4"
}
}
here is the tsconfig:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6","dom"],
"outDir": "lib",
"rootDir": "src",
"strict": false,
"esModuleInterop": true,
"resolveJsonModule": true
}
}
If you want to use namespace in nodejs side you need to export it also to use it in another module. Becuase namespace will be converted like this
engine.ts
namespace EngineSpace {
export class Engine {
public start() {
console.log('hello');
}
}
}
enigne.js
var EngineSpace;
(function (EngineSpace) {
class Engine {
start() {
console.log('hello');
}
}
EngineSpace.Engine = Engine;
})(EngineSpace || (EngineSpace = {}));
And if you want to use some property of another module in nodejs you need to export it and need to require it in another module.
Refer this for nodejs namespace
For the browser setup with typescript please refer this
Hope it helps you

Categories

Resources