I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5
Related
I'm running into an issue where I try to require a .jpg image.
When Googling I thought it had something to do with Jest but now when I start from a clean project, not having Jest as a dependency I get the same error.
What can be the issue?
This is the files I'm trying to run
server.js
// Import express framework
const express = require('express')
// Import routes
const visionAiRouter = require('./routes/vision-ai-route')
// Setup default port
const PORT = process.env.PORT || 4000
// Create express app
const app = express()
// Vision AI Route
app.use('/ai', visionAiRouter)
// Implement route for errors
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
// Start express app
app.listen(PORT, function() {
console.log(`Server is running on: ${PORT}`)
})
vision-ai-route.js
// Import
const express = require('express')
const visionAi = require('../controllers/vision-ai-controller')
// Create express router
const router = express.Router()
router.get('/', visionAi.labelDetection)
// Export
module.exports = router
vision-ai-controller.js
// Assets
const cat = require('./../data/cat.jpg')
// Create controller for GET request to '/users/all'
exports.labelDetection = async (req, res) => {
// Imports the Google Cloud client library
const vision = require('#google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
const [result] = await client.labelDetection(cat);
const labels = result.labelAnnotations;
const stringify = JSON.stringify(labels);
await res.json(stringify)
}
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"#google-cloud/vision": "^2.1.1",
"express": "^4.17.1",
"nodemon": "^2.0.4"
},
"devDependencies": {},
"scripts": {
"start": "nodemon server.js"
},
"author": "",
"license": "ISC"
}
Stacktrace
/Users/kod/Desktop/Code/Private/vision-ai/test/data/cat.jpg:1
����
^
SyntaxError: Invalid or unexpected token
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/Users/kod/Desktop/Code/Private/vision-ai/test/controllers/vision-ai-controller.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
You can't require a non-code file as require is meant to load executable code. The correct equivalent would be const cat = fs.readFileSync('./test/data/cat.jpg').
I'm litteraly pulling my hair out with this problem.
I can't use debugger with VSCode on my project, and i do not understand why.
The error :
app\server.ts:1
import app from './app'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1070:16)
at Module._compile (internal/modules/cjs/loader.js:1120:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
Process exited with code 1
So the problem is i have my source map in another folder than the bundled code, it's something like this :
server.js (bundled)
app
server.ts
app.ts
build
sourcemaps
server.js.map (bundled)
My launch.json :
"configurations": [
{
"name": "Debug Program",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/app/server.ts",
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/build/sourcemaps/*"
],
"skipFiles": [
"<node_internals>/**"
]
}
]
If i use the bundled server.js, the debugger works, but i can't have breakpoints on my ts files (so it's a little useless for me).
There is my other files :
webpack.config.js
module.exports = {
entry: './build/server/server.js',
mode: process.env.NODE_ENV,
target: 'node',
output: {
path: path.resolve(__dirname),
filename: 'server.js',
sourceMapFilename: 'build/sourcemaps/server.js.map',
devtoolModuleFilenameTemplate : '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
},
module: {
rules: [
{
test: /\.js$/,
enforce: 'pre',
include: [
__dirname + './build',
],
use: ['source-map-loader'],
}
]
},
externals: [ nodeExternals() ],
devtool: 'source-map',
resolve: {
extensions: ['.js']
},
stats: {
warningsFilter: ['Failed to parse source map'],
},
}
server.ts :
import app from './app'
import { config } from 'dotenv'
/* ################################################
Set Variables
################################################ */
config()
const port = process.env.SERVER_PORT
/* ################################################
Listening
################################################ */
const listen : Promise<any> = new Promise ((resolve, reject) => {
app.listen(port, () => {
resolve(port)
})
})
listen.then((port) => {
console.log(`Console launched on http://localhost:${ port }`)
})
listen.catch((err) => {
console.log(err)
})
app.ts :
import express from 'express'
import * as bodyParser from 'body-parser'
import { Routes } from './routes/routes'
import hbs from 'express-hbs'
class App {
public app: express.Application
public routePrv = new Routes()
constructor () {
this.app = express()
this.config()
this.setViewEngine()
this.prepareStatic()
this.mountRoutes()
}
/* ################################################
Config
################################################ */
private config(): void {
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({ extended: false }))
}
/* ################################################
Templating Engine
################################################ */
private setViewEngine(): void {
const viewDir = './app/views'
this.app.engine('hbs', hbs.express4({
partialsDir: viewDir + '/partials',
layoutsDir: viewDir + '/layouts',
extname: '.hbs'
}))
this.app.set('view engine', 'hbs')
this.app.set('views', viewDir + '/pages')
}
/* ################################################
Assets
################################################ */
private prepareStatic(): void {
this.app.use('/public', express.static('./build/assets'))
this.app.use('/dist', express.static('./build/dist'))
}
/* ################################################
Routes
################################################ */
private mountRoutes(): void {
this.routePrv.routes(this.app)
}
}
export default new App().app
Thank you !!
I found the problem
Finally, the problem was in the sourcemap, which were not taken in account by vscode, because of a poor configuration in the gulp tasks...
After making my sourcemap point to the server.ts, with the good content, everything works.
here iam using a cloud functions to create users i am using a express module when i try to deploy this code it deploying to cloud funtions with message that Error : Funtions did not deploy properly
const express = require('express');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceaccount = require('./ServiceAccountKey.json');
const app = express();
admin.initializeApp({
credential: admin.credential.cert(serviceaccount)
});
app.post('/',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
when i add this at end
module.exports = {
app
}
it showing funtion deployed but its not showing in cloud functions dashboard
what wrong am i doing here
here is the error what ima getting i cnat get whAT THE error is
⚠ functions[register(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:1:79)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
Functions deploy had errors with the following functions:
register
You code never uses the firebase-functions modules to declare a Cloud Function. Your functions variable is going unused. You can't just export any function an expect it to run - it has to be built by the SDK.
If you have an express app to deploy, you need to export it via an HTTP type function:
exports.app = functions.https.onRequest(app);
First, I think you need to change the endpoint of the url. Don't just put '/'. Maybe like '/user/create'.
app.post('/user/create',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
And in your firebase.json you should rewrite the url :
{
"functions": {
...
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/user/create",
"function": "register"
}
]
}
}
For more explanation, you can follow this tutorial.
I am developing a game based on pixijs, in which animation is generated using Adobe Animate and Pixi-Animate and all this setup is configured with nodejs 8.11.1 and webpack 4. But when I load my texture on Pixi Animate getting the following errors:
Here is my error what i am getting:
addChild
webpack:///./node_modules/pixi.js/lib/core/display/Container.js?:94:13
<anonymous>
webpack:///./src/index.js?:10:1
./src/index.js
http://localhost:9000/salmon.min.js:2786:1
__webpack_require__
http://localhost:9000/salmon.min.js:20:12
<anonymous>
webpack:///multi_(webpack)-dev-server/client?:2:18
[0]
http://localhost:9000/salmon.min.js:2797:1
__webpack_require__
http://localhost:9000/salmon.min.js:20:12
<anonymous>
http://localhost:9000/salmon.min.js:84:18
<anonymous>
http://localhost:9000/salmon.min.js:1:11
My Webpack Configuration is:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: './src/index.js',
mode:"development",
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'salmon.min.js'
},
plugins: [
new HtmlWebpackPlugin({template: './index.html'}),
new webpack.NamedModulesPlugin(),
],
devServer:{
port: 9000,
compress: true
},
module: {
rules: [
{
test: /\.js$/,
use: ["source-map-loader"],
enforce: "pre"
}
]
}
};
Is there anything I am missing?
I am teaching myself to use Nodejs with Redux and Express. I have a tag in my view, and that's it. Very, very basic. I am getting an error in my console that I don't understand:
Uncaught ReferenceError: process is not defined
at Object.<anonymous> (bundle.js:548)
at __webpack_require__ (bundle.js:20)
at Object.defineProperty.value (bundle.js:492)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:482)
at __webpack_require__ (bundle.js:20)
at __webpack_exports__.b (bundle.js:63)
at bundle.js:66
Can someone help me figure out what this means?
Here is my server.js file:
"use strict"
var express = require('express');
var app = express();
var path = require('path');
// MIDDLEWARE TO DEFINE FOLDER FOR STATIC FILES
app.use(express.static('public'))
app.get('/', function(req, res){
res.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(3000, function(){
console.log('app is listening');
})
Here is my app.js file:
"use strict"
import {createStore} from 'redux'
// STEP 3 define reducers
const reducer = function(state=0, action){
switch(action.type){
case "INCREMENT":
return state + action.payload;
break;
}
return state
}
// STEP 1 create the store
const store = createStore(reducer);
store.subscribe(function(){
console.log('current state is: ' + store.getState());
})
// STEP 2 create and dispatch actions
store.dispatch({type: "INCREMENT", payload: 1 })
Here is my webpack.config.js file:
var path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['./src/app.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
target: 'node',
watch: true,
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
}
Try adding this code to the plugin portion of your webpack.config
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production") //or "development"
}
});
You can read about why this might be your issue below. Basically you need to give webpack a NODE_ENV variable.
https://github.com/facebook/react/blob/f7850dd3d78d313a9e7774870e85c32719fbe233/docs/docs/getting-started.md