I've been looking around and can't seem to find a clear answer on this.
Is it possible to import an index.js file from a client directory using the directory name (omitting /index.js)? If so, how? This is a new project and I don't really want to bundle my code at this point.
The node version is v17.1.0.
File structure
package.json
server.js
src/
index.js
utils/
index.js
package.json
{
"type": "module",
"main": "server.js",
"scripts": {
"start": "nodemon --ignore src"
},
"devDependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.14"
}
}
server.js
import express from 'express'
express()
.use(express.static('src'))
.get('/', (_, res) => res.send(`
<script type="module" src="index.js"></script>`))
.listen(3000, () => console.log(`Running at http://localhost:3000`))
src/index.js
import { stuff } from './utils'
// Firefox: Loading module from “http://localhost:3000/utils/”
// was blocked because of a disallowed MIME type (“text/html”).
I've tried running the app with node --experimental-specifier-resolution=node server.js and tried adding express.static.mime.define({'text/javascript': ['js']}) to server.js, but neither worked for me.
Related
I am using my Solid-JS based web app to standalone using Electron, but the app does not work even if it built successfully.
When I check it with developer tool, it shows the error "Failed to load resource: net::ERR_FILE_NOT_FOUND" to my css and index.tsx files.
In React cases, usually just add {"homepage": "./"} to package.json works, but it does not work for my case.
I just share my package.json and electron.ts file to find the problem. (it is in public/ directory)
package.json
{
"name": "my-solid-project",
"author": "AAAA",
"version": "0.1.0",
"description": "",
"type": "commonjs",
"main": "./public/electron.js",
"homepage": "./",
"scripts": {
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "vitest",
"postinstall": "node ./fix-jest-dom.mjs",
"start-renderer": "cross-env BROWSER=none yarn start",
"start-main": "electron .",
"compile-main": "tsc ./public/electron.ts",
"start-main-after-renderer": "wait-on http://localhost:3000 && yarn start-main",
"electron-dev": "concurrently -n renderer, main 'yarn:start-renderer' 'yarn:start-main-after-renderer'",
"electron-dist": "yarn build && electron-builder --dir --config .electron-builder.config.cjs",
"predist": "yarn compile-main",
},
electron.ts
import * as path from 'path';
import * as url from 'url';
import { app, BrowserWindow } from 'electron';
import * as isDev from 'electron-is-dev';
import { join } from 'path';
const baseUrl: string = 'http://localhost:3000';
let mainWindow: BrowserWindow | null;
function createMainWindow(): void {
mainWindow = new BrowserWindow({
width: 1080,
height: 700,
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadURL(`file://${path.join(__dirname, '../index.html')}`);
mainWindow.webContents.openDevTools();
if (isDev) {
mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', (): void => {
mainWindow = null;
});
}
app.on('ready', (): void => {
createMainWindow();
});
app.on('window-all-closed', (): void => {
app.quit();
});
app.on('activate', (): void => {
if (mainWindow === null) {
createMainWindow();
}
});
The problem does not seem anything related to SolidJS but due to some malformed file path.
Edit: He was using absolute path in his config file.
I found out that vite build in my project imports resource files with absolute path.
You need to compile typescript files into JavaScript files in order to run in Electron renderer. So, there is no way to run index.tsx directly in Electron.
You application loads index.html file but it is not clear how you run your development server. Developers usually use something like this:
if (isDev) {
mainWindow.loadURL('http://localhost:3000');
} else {
mainWindow.loadFile(path.join(__dirname, 'index.html'));
}
Make sure your index.html file includes client code with their right paths.
In React cases, usually just add {"homepage": "./"} to package.json works
This is not a built-in Electron functionality. You must be using some package that mounts a react router.
If you are missing files in your executable file, make sure you bundle the required files in your final executable. You need to explicitly specify which files will be included in the bundle.
Here is a basic electron-vite-solid app: https://github.com/snnsnn/electron-vite-solid
Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.
The error I am getting is
Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js
Steps to Reproduce
With the following three files
src/index.js
export const sum = (a, b) => a + b;
test/index.spec.js
import { sum } from '../src/index';
const expect = require('chai').expect;
describe('Testing Index', () => {
it('Testing sum', () => {
expect(sum(7, 13)).to.equal(20);
});
});
package.json
{
"name": "mocha-debug",
"type": "module",
"main": "index.js",
"scripts": {
"test": "mocha \"./test/**/*.spec.js\""
},
"license": "ISC",
"devDependencies": {
"chai": "4.3.4",
"mocha": "9.1.4"
}
}
and using node v14.18.2, run yarn install and
yarn test
> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`
Notes
I've found a related issue that recommends using babel with --require #babel/register, but wasn't able to get over the error.
I've set up a test repo to make it easy to reproduce the issue
https://github.com/simlu/mocha-debug
Question
What am I doing wrong here? How do I get the tests to run successfully?
I solved it by just adding the file extension in my case I was importing my mongodb model so I imported with the file extension .ts
var Employee = require('../models/Employee.ts')
Which solved the issue
I'm new to Node.js, please help me.
What is wrong?
Using typescript, SQLite3 and Knex, with migration.
I get the error when running "yarn knex: migrate" or "knex migrate: latest":
$ knex migrate:latest
Requiring external module ts-node/register
Error: knex: Required configuration option 'client' is missing
These are my files:
package.json:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "ts-node-dev --transpile-only --ignore-watch node-modules --respawn
src/server.ts",
"knex:migrate": "knex --knexfile knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile knexfile.ts migrate:rollback"
},
"devDependencies": {
"#types/express": "^4.17.11",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"espress": "^0.0.0",
"express": "^4.17.1",
"knex": "^0.95.4",
"sqlite3": "^5.0.2"
}
}
knexfile.ts:
import path from'path';
module.exports = {
cliente: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'src', 'database', 'resp.sqlite')
},
migrations: {
directory: path.resolve(__dirname, 'src', 'database', 'migrations'),
},
useNullAsDefault: true,
};
Migration 00_create_organizacoes.ts:
import knex from 'knex';
export async function up(knex: knex) {
return knex.schema.createTable('organizacoes', table => {
table.increments('id').primary();
table.string('razaosocial_org').notNullable();
table.integer('atividade_org').notNullable();
table.timestamp('criacao_org').defaultTo(knex.fn.now());
table.timestamp('atualizacao_org').defaultTo(knex.fn.now());
});
}
export async function down(knex: knex) {
return knex.schema.droptable('organizacoes');
};
My file structure:
enter image description here
Unsuccessful in other treatments.
Looks like you have a typo in your knexfile.ts
The name of the missing property is client and not cliente
The Requiring external module ts-node/register message you get is not the issue, the issue is that in the knexfile.ts the client property is not read. From the example above change the cliente property to client and it is fixed.
What if you have no spelling error, client exist in your configuration, and you are getting this message? Are you using a env file? If yes, In your knexfile.ts print the value from your env file. If it returns undefined, it means that no value was read for the env file. Check if you have the dotenv package installed and configured properly. Also check that your env file has a key called client and the value is available and in the knexfile.ts ensure you are calling the right key from your env.
Finally if the problem is not solved and every other thing is in-place, require dotenv in your package.json file before running a command as shown below.
"migrate:latest": "ts-node -r dotenv/config ./node_modules/knex/bin/cli.js migrate:latest
The ts-node -r dotenv/config ensures that the details in the env file are added to the environment.
The ./node_modules/knex/bin/cli.js starts the knex cli so that the remaining part which is a knex command can be executed.
import functions from 'firebase-functions';
import UtilModuler from '#utilModuler'
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
import UtilModuler from '#utilModuler';
^^^^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:721:23)
Caveats
I'm using third party libraries(#utilModuler) which were written via import/exports. Possible workarounds:
Fork library and generate cjs file with rollup.
esm works like a charm but it cause unnesecary memory consumptions
Question: is there are a way how to use hybrid import cjs and esm in google cloud function?(except options which I described above)
Would be nice to use in deploy function something like --experimental-modules
It looks like, ESM support has been added by the latest version of the firebase CLI (https://github.com/firebase/firebase-tools/releases/tag/v9.15.0):
$ npm install -g firebase-tools # Get the latest firebase-cli
$ firebase deploy --only functions # Deploy as usual
and
You must select nodejs14 runtime.
You must manually include latest version of #google-cloud/functions-framework dependency.
e.g.
// package.json
...
"engines": {
"node": "14"
},
"type": "module",
"dependencies": {
"#google-cloud/functions-framework": "^1.9.0",
...
},
and an example function:
// index.js
import functions from "firebase-functions";
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
"devDependencies": {
"#babel/core": "^7.2.0",
"#babel/preset-env": "^7.2.0",
"#babel/register": "^7.0.0"
}
.babelrc
{
"presets": ["#babel/preset-env"]
}
entry point node.js app
require("#babel/register")({})
// Import the rest of our application.
module.exports = require('./index.js')
I stumbled upon this error while trying my first steps in webpack usage.
Just to reproduce the effect at a very basic level, I set up this micro folder like this:
node-test-2
main.js
package.json
webpack.config.js
With the following contents:
package.json
{
"name": "node-test-2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack && node bundle.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^2.2.0"
}
}
webpack.config.js
var path = require('path');
module.exports = {
entry : './main.js',
output : {
path : path.resolve(__dirname),
filename : 'bundle.js'
}
}
main.js
var http = require('http');
console.log("Creating Server");
var server = http.createServer(function(req, res){
console.log('Connection Estabilished!');
res.write('HELLO!');
res.end();
});
console.log("Listening on port " + 8000);
server.listen(8000);
Now, if I simply node main.js everything works as intended.
On the contrary, if I npm start, thus prompting webpack to bundle everything that's needed in the bundle.js fle and then running it, the error http.createServer is not a function error shows up when running.
Further checks show that the function seems not declared at all in the bundle.js file.
What am I missing here? Is this something webpack actually isn't meant for?
More, maybe meaningless, informations:
Running on Windows 10
Tested with node version 6.9 and 7.10
Tested with both webpack and webpack#beta at the time of writing
By default, Webpack targets browser environments, for which http.createServer() doesn't make much sense.
You can change the target by adding the following to your Webpack configuration:
entry : './main.js',
target : 'node',
...
https://webpack.js.org/configuration/target/