When I run the dev server, I got an error 'Uncaught ReferenceError: require is not defined' in external "url" - webpack-4

I have just started to study Webpack and trying to setup development environment based on Webpack4.
I put one script for executing dev server in package.json like below.
# package.json
"scripts": {
"dev": "webpack-dev-server --mode development",
}
However, there was an error message like below when I execute'npm run dev' on my terminal.
ERROR in ./node_modules/destroy/index.js
Module not found: Error: Can't resolve 'fs' in 'D:\webpack-setup\node_modules\destroy'
# ./node_modules/destroy/index.js 14:17-30
So, I installed 'webpack-node-externals' and put configuration in 'webpack.config.js' like below.
# install webpack-node-externals module
# npm install --save-dev webpack-node-externals
# webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'web',
externals: [nodeExternals()],
devServer: {
host: 'localhost',
port: 3000,
open: true
}
};
When a browser was opened, there was an error on a browser like below.
Uncaught ReferenceError: require is not defined
at eval (external_"url":1)
at Object.url (main.js:289)
at __webpack_require__ (main.js:20)
at Object.eval (webpack:///(:3000/webpack)-dev-server/client?:6:11)
at eval (webpack:///(:3000/webpack)-dev-server/client?:249:30)
at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:3000 (main.js:97)
at __webpack_require__ (main.js:20)
at eval (webpack:///multi_(:3000/webpack)-dev-server/client?:1:1)
at Object.0 (main.js:190)
at __webpack_require__ (main.js:20)
I'm not sure this error is related to 'webpack-node-externals' module or not,
but could I get some guide for solving this situation?

I think you have a problem in your config file. I ran a sample with this and it worked:
const nodeExternals = require('webpack-node-externals')
module.exports = {
target: 'web',
externals: [nodeExternals()],
devServer: {
host: 'localhost',
port: 3000,
open: true,
},
}

Related

Angular 11 Unit Test Code Coverage is Now Breaking

Prior to upgrading to Angular 11, I ran my unit tests with code coverage via the following command:
ng test --project my-app --code-coverage true
When I upgraded my project to Angular 11, I was still able to do my code coverage tests, but I started getting a message saying "'karma-coverage-istanbul-reporter' usage has been deprecated since version 11". It asked me to install karma-coverage and update karma.conf.js. So I did what it asked. I installed karma-coverage and karma via this command:
npm install karma karma-coverage --save-dev
As a result, I see in my package.json, under devDependencies, the entries for karma:
"karma": "^5.2.3",<br>
"karma-coverage": "^2.0.3"
I updated my karma.conf.js file. The following is what exists, everything was as it was originally except for my comments:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'), // NEWLY ADDED
// ORIGINALLY HERE NOW REMOVED require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
reporters: ['progress', 'kjhtml', 'coverage'],
// coverageIstanbulReporter NO LONGER HERE
//coverageIstanbulReporter: {
// dir: require('path').join(__dirname, '../../coverage/my-app'),
// reports: ['html', 'lcovonly', 'text-summary'],
// fixWebpackSourcePaths: true
//},
// coverReporter NEWLY ADDED
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
},
// THE FOLLOWING REMAINED AS IS
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
Having made this update, two things are happening and I can't figure out why.
When I run my normal code coverage command, I get the following error: "Server start failed on port 9876: Error: karma-coverage must be installed in order to run code coverage." I did install it, as my package.json indicates, but for some reason my project doesn't recognize this. In addition, if I add back the karma-coverage-istanbul-reporter require method to my conf.js file, coverage works fine, but I still get that deprecation message. Can anyone explain to me why I may be getting this error?
When I run my tests without coverage, I now get multiple warnings that I never got before, like: "Unable to determine file type from the file extension, defaulting to js.
To silence the warning specify a valid type for C:/Angular/my-project/projects/my-app/src/app/app.component.spec.ts in the configuration file." What would I need to do to resolve this?
EDIT: I found the answer. Inside the coverageReporter object, you need to add the fixWebpackSourcePaths property to true:
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
],
fixWebpackSourcePaths: true
},
The trick for me was to remove 'coverage' from the reporters. It should just be:
reporters: ['progress', 'kjhtml'],
The coverage report is then created as expected without weird warnings being thrown.
This seems to be the Angular way, have a look at the karma.conf.js generated by the ng new schematics.
Also, I found that the reporters must have a subdir field:
Doesn't work
reporters: [
{ type: 'html' }
}
Doesn't work
reporters: [
{ type: 'html', subdir: '' }
}
Works:
reporters: [
{ type: 'html', subdir: 'report-html' }
}

ERR_CONNECTION_REFUSED with Django and Vue.js bundle files

I've built a simple SPA CRUD web app with Django, Vue and Docker(-compose).
Since I've finished developing the app, I'm now preparing for the production environment, that is, using bundle.js and bundle.css files.
When I try to load the main page, http://localhost:8000, no CSS or JS
are being loaded because I'm getting this error in the browser's console:
GET http://0.0.0.0:8080/bundle.css net::ERR_CONNECTION_REFUSED
GET http://0.0.0.0:8080/bundle.js net::ERR_CONNECTION_REFUSED
I really don't know why it is giving that error or how to fix it.
This is my vue.config.js file:
const webpack = require("webpack");
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
filenameHashing: false,
configureWebpack: {
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
},
chainWebpack: config => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.optimization.delete("splitChunks");
config.resolve.alias.set("__STATIC__", "static");
config.devServer
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.disableHostCheck(true)
.headers({ "Access-Control-Allow-Origin": ["*"] });
},
// uncomment before executing 'npm run build'
css: {
extract: {
filename: "bundle.css",
chunkFilename: "bundle.css"
}
}
};
This is part of my settings.py file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "assets"),
os.path.join(BASE_DIR, "frontend/dist"),
]
# STATIC_ROOT = "" # The absolute path to the dir for collectstatic
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json'),
}
}
When I run the npm run build command I get notified that both the bundle.css and the bundle.js files have been generated:
File Size Gzipped
dist/bundle.js 150.73 KiB 51.05 KiB
dist/bundle.css 192.06 KiB 26.89 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
I really don't know why it is giving that ERR_CONNECTION_REFUSEDerror or how to fix it.
For production remove publicPath from your vue config file, I suppose you used that for development purposes, but in production you should only create the bundle and serve it to the user.
What's probably happening is that in your Docker setup you don't have the webpack dev server running (and you don't need it), thus you hit a connection refused error.

Error deploying meteor app on aws

Here is the mup.js:
module.exports = {
servers: {
one: {
host: '52.41.186.122',
username: 'ubuntu',
pem: 'aws-key/xanthelabs.pem'
// password:
// or leave blank for authenticate from ssh-agent
}
},
meteor: {
name: 'deep-app',
path: '/home/cortana/Desktop/deep-app',
servers: {
one: {}
},
buildOptions: {
serverOnly: true,
},
env: {
ROOT_URL: 'http://52.41.186.122:8888',
MONGO_URL: 'mongodb://localhost/meteor'
},
//dockerImage: 'kadirahq/meteord'
deployCheckWaitTime: 60
},
mongo: {
oplog: true,
port: 27017,
servers: {
one: {},
},
},
};
The error is:
Started TaskList: Start Meteor
[52.41.186.122] - Start Meteor
[52.41.186.122] - Start Meteor: SUCCESS
[52.41.186.122] - Verifying Deployment
[52.41.186.122] x Verifying Deployment: FAILED
-----------------------------------STDERR-----------------------------------
npm WARN deprecated semver behavior.
npm WARN package.json meteor-dev-bundle#0.0.0 No description
npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
npm WARN package.json meteor-dev-bundle#0.0.0 No README data
npm WARN cannot run in wd meteor-dev-bundle#0.0.0 node npm-rebuild.js (wd=/bundle/bundle/programs/server)
=> Starting meteor app on port:80
assert.js:93
throw new assert.AssertionError({
^
AssertionError: "undefined" === "function"
at wrapPathFunction (/bundle/bundle/programs/server/mini-files.js:77:10)
at Object.<anonymous> (/bundle/bundle/programs/server/mini-files.js:108:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/bundle/bundle/programs/server/boot.js:9:13)
at Module._compile (module.js:456:26)
-----------------------------------STDOUT-----------------------------------
To see more logs type 'mup logs --tail=50'
----------------------------------------------------------------------------
(node:8968) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error:
-----------------------------------STDERR-----------------------------------
npm WARN deprecated semver behavior.
npm WARN package.json meteor-dev-bundle#0.0.0 No description
npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
npm WARN package.json meteor-dev-bundle#0.0.0 No README data
npm WARN cannot run in wd meteor-dev-bundle#0.0.0 node npm-rebuild.js (wd=/bundle/bundle/programs/server)
=> Starting meteor app on port:80
assert.js:93
throw new assert.AssertionError({
^
AssertionError: "undefined" === "function"
at wrapPathFunction (/bundle/bundle/programs/server/mini-files.js:77:10)
at Object.<anonymous> (/bundle/bundle/programs/server/mini-files.js:108:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/bundle/bundle/programs/server/boot.js:9:13)
at Module._compile (module.js:456:26)
-----------------------------------STDOUT-----------------------------------
To see more logs type 'mup logs --tail=50'
----------------------------------------------------------------------------
Everything has been successfully setup. I dont understand what is throwing the error. Please explain the error and its reasons along with the solution. Thanks
About the system:
OS: ubuntu 16.04
deployment OS: Ubuntu 14.04 (on aws)
meteor : v1.4.1.2
Edit:
On using meteor-up fork suggested, I am getting this error:
[52.41.186.122] - Installing Node.js
[52.41.186.122] - Installing Node.js: SUCCESS
[52.41.186.122] - Installing PhantomJS
[52.41.186.122] - Installing PhantomJS: SUCCESS
[52.41.186.122] - Setting up Environment
[52.41.186.122] - Setting up Environment: SUCCESS
[52.41.186.122] - Copying MongoDB configuration
[52.41.186.122] x Copying MongoDB configuration: FAILED
Received exit code 0 while establishing SFTP session
The mup.js file I have is:
{
// Server authentication info
"servers": [
{
"host": "52.41.186.122",
"username": "ubuntu",
// "password": "ubuntu"
// or pem file (ssh based authentication)
"pem": "aws-key/xanthelabs.pem"
}
],
// Install MongoDB in the server, does not destroy local MongoDB on future setup
"setupMongo": true,
// WARNING: Node.js is required! Only skip if you already have Node.js installed on server.
"setupNode": true,
// WARNING: If nodeVersion omitted will setup 0.10.43 by default. Do not use v, only version number.
"nodeVersion": "4.4.7",
// Install PhantomJS in the server
"setupPhantom": true,
// Show a progress bar during the upload of the bundle to the server.
// Might cause an error in some rare cases if set to true, for instance in Shippable CI
"enableUploadProgressBar": true,
// Application name (No spaces)
"appName": "deep-app",
// Location of app (local directory)
"app": "/home/cortana/Desktop/deep-app",
// Configure environment
"env": {
"PORT": 8888,
"ROOT_URL": "http://52.41.186.122",
"MONGO_URL": "mongodb://localhost/meteor"
},
// Meteor Up checks if the app comes online just after the deployment
// before mup checks that, it will wait for no. of seconds configured below
"deployCheckWaitTime": 15
}
what is wrong here?
i had the same issues. add dockerImage: "abernix/meteord:base", to you meteor part of MUP.json.
If it's still not working. replace Flow Router with React Router

Rails app deployment with AZK fail on Digital Ocean

I'm trying to push a very simple rails app on a DigitalOcean droplet. Unfortunatly, i'm enable to continue the deployment : i get stuck with a very elusive error message :
info: [agent] get agent status
info: [agent] agent is running: true
info: [agent] get agent status
info: [agent] agent is running: true
info: [agent] get agent status
info: [agent] agent is running: true
info: [agent] get agent status
info: [agent] agent is running: true
info: Connecting to http://192.168.50.4:2375
PLAY [all] *********************************************************************
TASK [setup] *******************************************************************
fatal: [default]: FAILED! => {"changed": false, "failed": true, "module_stderr": "", "module_stdout": "/bin/sh: 1: /usr/bin/python: not found\r\n", "msg": "MODULE FAILURE", "parsed": false}
NO MORE HOSTS LEFT *************************************************************
to retry, use: --limit #playbooks/setup.retry
PLAY RECAP *********************************************************************
default : ok=0 changed=0 unreachable=0 failed=1
Am i the only one who ever encounter this problem ?
Here is my Azkfile too :
/**
* Documentation: http://docs.azk.io/Azkfile.js
*/
// Adds the systems that shape your system
systems({
'apptelier-website': {
// Dependent systems
depends: [],
// More images: http://images.azk.io
image: {docker: 'azukiapp/ruby:2.3.0'},
// Steps to execute before running instances
provision: [
"bundle install --path /azk/bundler"
],
workdir: "/azk/#{manifest.dir}",
shell: "/bin/bash",
command: ["bundle", "exec", "rackup", "config.ru", "--pid", "/tmp/ruby.pid", "--port", "$HTTP_PORT", "--host", "0.0.0.0"],
wait: 20,
mounts: {
'/azk/#{manifest.dir}': sync("."),
'/azk/bundler': persistent("./bundler"),
'/azk/#{manifest.dir}/tmp': persistent("./tmp"),
'/azk/#{manifest.dir}/log': path("./log"),
'/azk/#{manifest.dir}/.bundle': path("./.bundle")
},
scalable: {"default": 1},
http: {
domains: [
'#{env.HOST_DOMAIN}', // used if deployed
'#{env.HOST_IP}', // used if deployed
'#{system.name}.#{azk.default_domain}' // default azk domain
]
},
ports: {
// exports global variables
http: "3000/tcp"
},
envs: {
// Make sure that the PORT value is the same as the one
// in ports/http below, and that it's also the same
// if you're setting it in a .env file
RUBY_ENV: "production",
RAILS_ENV: "production",
RACK_ENV: 'production',
WORKER_RETRY: 1,
BUNDLE_APP_CONFIG: '/azk/bundler',
APP_URL: '#{system.name}.#{azk.default_domain}'
}
},
deploy: {
image: {docker: 'azukiapp/deploy-digitalocean'},
mounts: {
'/azk/deploy/src': path('.'),
'/azk/deploy/.ssh': path('#{env.HOME}/.ssh'), // Required to connect with the remote server
'/azk/deploy/.config': persistent('deploy-config')
},
// This is not a server. Just run it with `azk deploy`
scalable: {default: 0, limit: 0},
envs: {
GIT_REF: 'master',
AZK_RESTART_COMMAND: 'azk restart -Rvv',
BOX_SIZE: '512mb'
}
}
});
Thanks for the help !
Edouard, nice to meet you. I'm from azk core team and I'm not sure if you're using the latest deployment image.
Please follow these steps to update it:
adocker pull azukiapp/deploy-digitalocean:0.0.7;
Edit the deploy system in your Azkfile and add the tag 0.0.7 to the used deployment image to ensure we're using the latest one. It should be like: image: {docker: 'azukiapp/deploy-digitalocean:0.0.7'};
Next, be sure you have the env DEPLOY_API_TOKEN set in your .env file. If you don't have it set yet, take a look on the Step 7 of the article we've published on DigitalOcean Community Tutorials: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-rails-app-with-azk#step-7-%E2%80%94-obtaining-a-digitalocean-api-token
Finally, re-run the deploy command:
azk deploy clear-cache;
azk deploy
Please let me know if this is enough to solve your problem.

Webpack not compiling files on Heroku

I want to use Webpack to compile files for my Django app on Heroku, and am using webpack-bundle-tracker to keep track of the modules created in webpack-stats.json. When I run webpack locally, it compiles all the files and bundles them into the output directory, no problem. But when I run webpack on Heroku, it shows me that all the chunks were emitted, but none of the files appear in the output directory. When I check the content of webpack-stats.json it always says "status" : "compiling".
Here's the content of my webpack.config.js.
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name].js',
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{ test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react']
}
}
]
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx'],
},
}
I want webpack to bundle my assets the same way on heroku as it does on my local machine. How can I accomplish that?