module.exports function is not a function - javascript

I'm trying to require an endpoints.js file into my webpack.config.js
Expected
endpoints.js gets required correctly then sets a custom api file depending on the process.env.NODE_ENV
Results
const api = endpoints(process.env.NODE_ENV);
TypeError: endpoints is not a function
Webpack.config.js
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);
console.log('webpack endpoints', endpoints);
console.log('webpack api', api);
endpoints.js
module.exports = {
endpoints: function(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
}
I also tried the following, but got an Unexpected token export
export default function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
};

Ah I was using module.exports wrong, however it looked correct according to this site.
This is how I needed to use module.exports to export out my endpoints function.
function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
module.exports = endpoints;

Related

Cannot read properties of undefined (reading 'match') at getLocalIdent

i'm trying to make build script. so i can build with webpack it kinda like this
build.server.js
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
process.on('unhandledRejection', err => {
throw err;
});
require('../config/env');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.server');
const paths = require('../config/paths');
function build() {
console.log('Creating server build');
fs.emptyDirSync(paths.ssrBuild);
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, status) => {
if (err) {
console.log(err);
return;
}
console.log(status.toString());
});
});
}
build();
after i code this and type node scripts/build.server.js , this error comes out.
Cannot read properties of undefined (reading 'match')
at getLocalIdent (C:\Users\jhs00\OneDrive\바탕 화면\공부자료\ssrProject\ssrproject\node_modules\react-dev-utils\getCSSModuleLocalIdent.js:20:49)
getLoslIdent is in here (webpack.config.server.js)
const nodeExternals = require('webpack-node-externals')
const webpack = require('webpack');
const paths = require('./paths');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
...
i searched similar question and tried delete package-lock.json, node_modules and reinstall it. but didn't work. what should i do?

How do you dynamically module.export all files in a folder?

I'm trying to dynamically export modules. I'm close but can't figure out how to fix my syntax.
Hard coded:
// index.js inside folder 'models'
const { User } = require('./User');
const { Token } = require('./Token');
const { Session } = require('./Session');
module.exports = {
User,
Token,
Session,
};
Dynamically coded (doesn't work):
// index.js inside folder 'models'
const fs = require('fs');
const path = require('path');
module.exports = () => {
fs.readdirSync(__dirname).forEach((file) => {
if (file === 'index.js') return false;
const fullName = path.join(__dirname, file);
if (file.toLowerCase().indexOf('.js')) {
// I think this somehow needs to be destructured like
// `return {require(fullName)}` or
// `require(fullName)[fullName]` I think
require(fullName);
}
});
};
Elsewhere in my code, I initialize it based on the folder name:
// server.js
require('./models')();
Your dynamic export will not work because you are not returning anything to the exported function.
Try this code as your dynamic model export file
// index.js inside folder 'models'
const fs = require('fs')
const path = require('path')
const models = {}
fs.readdirSync(__dirname)
.filter(file => file !== 'index.js')
.forEach(file => {
const fullName = path.join(__dirname, file)
if (file.toLowerCase().endsWith('.js')) {
// Removes '.js' from the property name in 'models' object
const [filename] = file.split('.')
models[filename] = require(fullName)[filename]
}
})
module.exports = models
This approach no longer exports a function so your require in server.js should now look like this
// server.js
require('./models');

How to create/generate/export a file from my webpack 2 config to be used inside of my React code?

I am passing in NODE_ENV variables into my webpack.config from package.json in order to return an object that either contains API endpoints for localhost or production.
1) package.json
"scripts": {
"dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
"prod": "NODE_ENV=production webpack -p",
"build": "NODE_ENV=production webpack -p"
}
2) endpoints.js
function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
module.exports = endpoints;
3) webpack.config
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);
console.log('webpack api', api);
module.exports = {
context: src,
entry: [
"./index.js"
],
output: {
path: dist,
// ....
Here below I can see the console.log of the const api.
Now my question is, how do I now generate or export out an actual file api to be used inside of my src/services/api file:
import axios from 'axios'
// import api from '../../webpack.config' <-- ?
// import api from '../../api.js <-- ?
const log = (method, err) => {
console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
return null;
};
export const userLogin = (username, password) => {
const post_data = { username, password };
return axios.post('http://localhost/app/api/login', post_data) // <-- api to be used here
.then(res => res)
.catch((err) => log('api.userLogin', err));
};
I think this is an XY problem. You could generate the files with a bit of Node (something like fs.writeFileSync('api.js', contents), or you could do it with a bit of shell scripting, but you could also just use env in your code using DefinePlugin (example: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }). Then you'd be able to access env in your code directly.

Webpack dist: index.html is a blank page

I'm pretty new to Webpack, and have followed this tutorial to add authentication to a React app I have been working on.
It all works fine in development, however I get a blank page when trying to run the distribution files.
Here's my webpack.config.js:
const NODE_ENV = process.env.NODE_ENV;
const dotenv = require('dotenv');
const webpack = require('webpack');
const fs = require('fs');
const path = require('path'),
join = path.join,
resolve = path.resolve;
const getConfig = require('hjs-webpack');
const isDev = NODE_ENV === 'development';
const isTest = NODE_ENV === 'test';
const root = resolve(__dirname);
const src = join(root, 'src');
const modules = join(root, 'node_modules');
const dest = join(root, 'dist');
var config = getConfig({
isDev: isDev,
in: join(src, 'app.js'),
out: dest,
html: function (context) {
return {
'index.html': context.defaultTemplate({
title: 'My Title',
publicPath: isDev ? 'http://localhost:3000/' : 'http://localhost:9000/',
meta: {
'name': 'My name',
'description': 'My desc'
}
})
}
}
});
// ENV variables
const dotEnvVars = dotenv.config();
const environmentEnv = dotenv.config({
path: join(root, 'config', `${NODE_ENV}.config.js`),
silent: true,
});
const envVariables =
Object.assign({}, dotEnvVars, environmentEnv);
const defines =
Object.keys(envVariables)
.reduce((memo, key) => {
const val = JSON.stringify(envVariables[key]);
memo[`__${key.toUpperCase()}__`] = val;
return memo;
}, {
__NODE_ENV__: JSON.stringify(NODE_ENV)
});
config.plugins = [
new webpack.DefinePlugin(defines)
].concat(config.plugins);
// END ENV variables
// CSS modules
const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`;
const matchCssLoaders = /(^|!)(css-loader)($|!)/;
const findLoader = (loaders, match) => {
const found = loaders.filter(l => l && l.loader && l.loader.match(match))
return found ? found[0] : null;
}
// existing css loader
const cssloader =
findLoader(config.module.loaders, matchCssLoaders);
const newloader = Object.assign({}, cssloader, {
test: /\.module\.css$/,
include: [src],
loader: cssloader.loader.replace(matchCssLoaders, `$1$2?modules&localIdentName=${cssModulesNames}$3`)
})
config.module.loaders.push(newloader);
cssloader.test = new RegExp(`^(?!.*(module|bootstrap)).*${cssloader.test.source}`)
cssloader.loader = newloader.loader
config.module.loaders.push({
test: /bootstrap\.css$/,
include: [modules],
loader: 'style-loader!css-loader'
})
// postcss
config.postcss = [].concat([
require('precss')({}),
require('autoprefixer')({}),
require('cssnano')({})
])
// END postcss
// Roots
config.resolve.root = [src, modules]
config.resolve.alias = {
'css': join(src, 'styles'),
'containers': join(src, 'containers'),
'components': join(src, 'components'),
'utils': join(src, 'utils'),
'styles': join(src, 'styles')
}
// end Roots
// Testing
if (isTest) {
config.externals = {
'react/addons': true,
'react/lib/ReactContext': true,
'react/lib/ExecutionEnvironment': true,
}
config.module.noParse = /[/\\]sinon\.js/;
config.resolve.alias['sinon'] = 'sinon/pkg/sinon';
config.plugins = config.plugins.filter(p => {
const name = p.constructor.toString();
const fnName = name.match(/^function (.*)\((.*\))/)
const idx = [
'DedupePlugin',
'UglifyJsPlugin'
].indexOf(fnName[1]);
return idx < 0;
})
}
// End Testing
module.exports = config;
I am serving the files using express using this script:
var express = require('express')
var app = express()
var path = require('path');
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname, 'dist/index.html'));
});
app.listen(9000, function () {
console.log('Example app listening on port 9000!')
})
All I get is a blank page with this markup:
<!doctype html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<title>My title</title>
<link rel="stylesheet" href="http://localhost:9000/stylesheet.css"/>
</head>
<body>
<div id="root"></div>
<script src="http://localhost:9000/javascript.js"></script>
</body>
Not sure what I'm missing, there doesn't seem to be any JS executing at all, and I'm not sure how to go about debugging minified JS...
Any help or pointers would be greatly apreciated.
Thanks
Your express server isn't configured to serve static files (other than the html). Add the express.static middleware before the wildcard route.

Reuse objects define in modules

I defined a logger with 2 different files and use it like this:
main.js
var config = require('./config');
var log = require('./services/logger')(config);
log.logger.info("Info Logging");
config.js
var config = {};
var PRODUCTION = process.env.NODE_ENV === "production";
config.log = {
level : 'info'
};
module.exports = config;
logger.js
module.exports = function (config) {
var winston = require('winston');
var logger = new(winston.Logger)({
transports : [new(winston.transports.Console)({
level : config.log.level
})]
});
var winstonStream = {
write : function (message, encoding) {
logger.info(message.slice(0, -1));
}
};
return {
logger : logger,
expressStreamLogger : winstonStream
};
};
Issue
In another file I want to use the logger (log.logger). Should I repeat the following require each time I need to use the logger?
var config = require('./config');
var log = require('./services/logger')(config);
log.logger.info("Info Logging");

Categories

Resources