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/
Related
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.
So I have a project that is html and javascript. You click index.html and it opens a 2D simulation in the browser. I'd like to package this as a standalone executable (.exe). I know there are other methods before I get suggestions but I want to do this with node, if possible.
To trigger this with node I've simply created an app.js that executes 'npm start', which in turn executes 'start index.html'.
I've had great success with pkg (https://www.npmjs.com/package/pkg) when its just a pure script but when I compile this project as an exe it WILL open in the browser and work fine. Issue is if I then move the executable from the original folder (eg to the desktop) it no longer works. I imagine this is because it is not including all of the files I need.
So far I have tried the following:
I compile with pkg . -t host.
I've tried including all files with 'glob'(), like so:
var glob = require( 'glob' )
, path = require( 'path' );
glob.sync( './html5/**/**/*.js' ).forEach( function( file ) {
require( path.resolve( file ) );
});
glob.sync( './html5/**/**/*.css' ).forEach( function( file ) {
require( path.resolve( file ) );
});
But this returns an error regarding window ('window is not defined'). I worked around this by adding:
if (typeof window !== "undefined") {
window.globalProvideData('stuff', 'more stuff');
}
every time I got the error but eventually it was giving me errors I can't figure out.
So, how can I include all files so it behaves as it does while in the root folder?
EDIT: Here's the folder structure and my package.json:
folder structure
package.json:
{
"name": "test_story",
"version": "1.0.0",
"description": "testing story exe",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "start story.html"
},
"bin": "app.js",
"author": "",
"license": "ISC",
"dependencies": {
"glob": "^7.1.6",
"pkg": "^4.5.1"
},
"pkg": {
"assets": [
"html5/**/*",
"mobile/*.jpg",
"node_modules/**/*",
"story_content/**/*"
]
}
}
One simple trick to avoid the root folder would be to run batch files that launch your directories for you. Also, to insure all files have been transferred correctly you could check the folder size and compare. This is how FTP often works.
I have recently upgraded from now v1 to v2.
Everything works locally with now dev and all pages reload without any problems. However when I push to prod with now --prod and navigate to a page everything works as expected, however if I reload the page I will take to the error page with an error of 404
I must admit i am finding the lines a little blurry on how I should setup my project since the move to v2. I am so sure its to do with my routing... but I always thought it took the routes directly from my folder structure?
To add to the confusion, if you reload, you will get a 404, however from that 404 error page, if you use the navigation the site will render without any problems.
According to the Docs, it should pick up the name from the filesystem, which i believe it does, as it navigates there initially.
By default, routing is defined by the filesystem of your deployment.
For example, if a user makes a request to /123.png, and your now.json
file does not contain any routes with a valid src matching that path,
it will fallback to the filesystem and serve /123.png if it exists.
now.json
{
"version": 2,
"builds": [
{ "src": "next.config.js", "use": "#now/next" }
],
}
Folder structure
next.config.json
const webpack = require('webpack')
const withCSS = require('#zeit/next-css')
module.exports = withCSS({
webpack: (config, {}) => {
const originalEntry = config.entry
config.entry = async () => {
const entries = await originalEntry()
if (entries['main.js'] && !entries['main.js'].includes('./polyfills.js')) {
entries['main.js'].unshift('./polyfills.js')
}
return entries
}
return config
},
env: {
env: process.env.NODE_ENV,
},
})
But yes, I am stuck and would be eternally grateful for some help :)
Package.json
I am unsure if this is helpful to know for the problem, but here is my scripts.
"scripts": {
"build": "next build",
"dev:inspect": "NODE_ENV=development nodemon --inspect server.js",
"start": "now dev",
"test": "echo \"Error: no test specified\" && exit 0",
"lint-scripts": "eslint './{Frontend/**,test/**,config/**,.}/*.js'",
"lint-styles": "stylelint './Frontend/**/*.css'",
"eslint": "eslint . --fix",
"lint": "npm run lint-scripts && npm run lint-styles",
"commit": "npx git-cz"
},
[Edit]
"routes": [
{"src": "/index", "dest": "/" },
{"src": "/charts", "dest": "/charts" }
]
Make a vercel.json and paste the redirect rules code. Save the file in your root directory, then redeploy.
{
"routes": [{ "src": "/[^.]+", "dest": "/", "status": 200 }]
}
Webpack provides the example below in its shimming documentation. In the global exports portion of that page, it gives the following example.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve('globals.js'),
use: exports-loader?file,parse=helpers.parse
}
]
}
}
./src/globals.js
var file = 'blah.txt';
var helpers = {
test: function() { console.log('test something'); },
parse: function() { console.log('parse something'); }
};
But when I attempt to build, I get:
ERROR in ./webpack.config.js
Module not found: Error: Can't resolve 'globals.js' in '/workspace/my-app'
Why is globals.js not resolving, and why does the example in their documentation assume it will? Am I missing something? Thanks.
Getting this to work with a global exports-loader configuration
I have this working with the following setup:
src/deps.js // this file just declare a global file variable
const file = 'this is the file';
src/app.js // entry point of the webpack bundle. It import's deps.js (even if deps.js does not have an export statement, thanks to export-loader):
import file from './deps.js'
console.log(file);
webpack.config.js // webpack configuration file
module.exports = {
entry: __dirname + '/src/app.js',
mode: 'development',
module: {
rules: [
{
test: /deps.js/,
use: 'exports-loader?file',
}
]
}
}
package.json // so we can run webpack locally to the project
{
"name": "exports-loader-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"webpack": "node_modules/webpack/bin/webpack.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"exports-loader": "^0.7.0",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
}
}
With this setup, assuming webpack.config.js, package.json and src/ are in the root of the project, do:
$ npm run webpack
To bundle the scripts, then:
$ node dist/main.js to check that the file variable is being loaded (to load this in a browser will do the same).
Getting this to work with an import specific configuration.
(this comes from this other answer).
In order to do so, you need to use just the exports-loader, without any further configuration when you load it in the webpack.config.js:
use: 'exports-loader',
And then specify the variables to wrap in an export clause in every import statement:
import file from 'exports-loader?file!./deps.js'
Why the require.resolve() syntax is not working?
I really don't know. The test clause expects a regex as far as I know (that's why it is called test in fact, because of the test method of regex's in javascript) and I'm not used to other kind of valid syntaxes. I see that in your snippet:
module.exports = {
module: {
rules: [
{
test: require.resolve('globals.js'),
use: exports-loader?file,parse=helpers.parse
}
]
}
}
The use value does not have string quotes. I wonder if this is broking the config and then you get a misleading error, I don't know. I actually believe you just didn't paste the quotes when copy and pasting to stack overflow.
I am trying to get the code coverage in MOCHA JS test. I am using the blanket and the but I am getting 0 % coverage 0 SLOC why I am not understanding.
my package.json is
{
"name": "basics",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha && mocha test --require blanket --reporter html-cov > coverage.html"
},
"author": "",
"license": "MIT",
"devDependencies": {
"chai": "~2.2.0",
"mocha": "~2.2.4",
"blanket": "~1.1.6",
},
"config": {
"blanket": {
"pattern": ["index.js"],
"data-cover-never": "node_modules"
}
}
}
and index.js is
exports.sanitize = function(word){
return word.toLowerCase().replace(/-/g, ' ');
}
exports.testToString = function(){
return word.toLowerCase().replace(/-/g, ' ');
}
and indexSpec.js which is under test folder is
var chai = require('chai');
var expect = require('chai').expect;
var word = require('../index.js');
describe ('sanitize', function(){
it('String matching ', function(){
var inputWord = 'hello WORLD';
var outputWord = word.sanitize(inputWord);
expect(outputWord).to.equal('hello world');
expect(outputWord).to.not.equal('HELLO WORLD');
expect(outputWord).to.be.a('string');
expect(outputWord).not.to.be.a('number');
});
it('Checke hyphen ', function(){
var inputWord = 'hello-WORLD';
var outputWord = word.sanitize(inputWord);
expect(outputWord).to.equal('hello world');
});
} )
Paul is right. There is no point in using buggy library. Steps for making this code work with Istanbul:
Install Istanbul globally npm install -g istanbul
Change script section in package.json
"scripts": {
"test": "mocha",
"coverage": "istanbul cover node_modules/mocha/bin/_mocha -- -R spec"
},
Run test by typing npm test
Generage coverage report: npm run coverage
Coverage report will be available in coverage/lcov-report/index.html
Get blanket from the git repo. I don't know what's wrong with their npm package, but it didn't work for me either.
Getting the module from git repo works fine.
Make the below changes in your package.json file
"devDependencies": {
"chai": "~2.2.0",
"mocha": "~2.2.4",
"blanket": "git://github.com/alex-seville/blanket.git"
},
I had this problem and added a blanket.js file in my root directory as recommended by Neilskrijger here ... https://github.com/alex-seville/blanket/issues/361 .
I then set my blanket pattern in my package.json to '/lib' which was the root of my source code and it worked. The forward slash was required. My test script was "mocha --require blanket -R html-cov --recursive> coverage.html".
It seems like a lot of us have used the same tutorial and met the same problem.
I have tried all hints given on this page (tried with node versions: node-v4.3.1 and node-v5.7.0) + a few more without any luck
I ended up with another package Istanbul, which I should have done from the start since I normally use the stats as a indicator of which package to use (Its used by so many more users).
First try with this package and it worked :-)
I added this to the script section of package.json:
"coverage" : "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- -R spec"