Getting an error when running my webpack-built React app - the error is as follows:
webpack-internal:///1495:3
var crypto = require('crypto');
^
TypeError: require is not a function
at eval (webpack-internal:///1495:3:14)
at Object.<anonymous> (/path/to/project/build/main.js:9739:1)
at __webpack_require__ (/path/to/project/build/main.js:21:30)
at eval (webpack-internal:///1494:1:20)
at Object.<anonymous> (/path/to/project/build/main.js:9733:1)
at __webpack_require__ (/path/to/project/build/main.js:21:30)
at eval (webpack-internal:///692:8:18)
at Object.<anonymous> (/path/to/project/build/main.js:4515:1)
at __webpack_require__ (/path/to/project/build/main.js:21:30)
at eval (webpack-internal:///1491:12:23)
I can't figure out which module this error is coming from. I am running my project by this command:
NODE_ENV=development nodemon --watch build/ build/main.js
Here is my webpack config:
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const webpackConfig = {
context: path.join(__dirname, '..'),
entry: ['babel-polyfill', path.join(__dirname, '../src/entry.js')],
target: 'node',
output: {
path: path.resolve(__dirname, '../build'),
publicPath: '/',
libraryTarget: 'commonjs2',
filename: 'main.js'
},
resolve: {
modules: [
path.join(__dirname, '../src'),
path.join(__dirname, '../server'),
'node_modules'
],
extensions: ['.js', '.jsx', '.json']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(png|gif|jpe?g|ico|eot|svg|ttf|woff2?)$/,
loader: 'file-loader',
options: {
context: 'src/app/assets/',
outputPath: 'dist/',
name: '[path][name].[ext]?[hash]',
//limit: 10000
}
}
]
},
node: {
net: 'empty',
tls: 'empty',
dns: 'empty',
fs: 'empty',
mysql: 'empty',
__dirname: true
},
plugins: [
// hot reload new webpack.HotModuleReplacementPlugin(),
new webpack.IgnorePlugin(/webpack-stats\.json$/),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
API_HOST: JSON.stringify(process.env.API_HOST),
API_PORT: JSON.stringify(process.env.API_PORT)
},
}),
],
externals: ['mysql', 'bindings']
}
if (process.env.NODE_ENV === 'development') {
webpackConfig.devtool = 'eval-source-map'
}
module.exports = webpackConfig
The file is being built with this command:
./node_modules/.bin/webpack --display-error-details --config webpack/webpack.config.js
The version of webpack I am using is 3.0.0.
If you still have a require in your bundle, it means that some ES6 file has not been transpiled by Babel.
I can see that you exclude node_modules from babel-loader...
Can you try removing the exclusion and see if it's any better?
Also, can you search for "require('crypto')" in all files arborescence?
Last, you say that it's a React app but babel-loader only transpiles .js files, not .jsx... Can you try changing loader's test to /\.jsx?$/ ?
Related
My webpack.config.js is :
const path = require('path');
module.exports = {
entry: './app.ts',
target: 'node',
node: {
__dirname: true
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
When I build my project and run it I am getting the following error:
(node:51071) UnhandledPromiseRejectionWarning: Error: Cannot find module '../gather/gatherers/css-usage'
at webpackEmptyContext (webpack:///./node_modules/lighthouse/lighthouse-core/config_sync?:2:10)
at Function.requireGathererFr
This error is raised from a 3rd party library I am using - lighthouse.
How to fix this error ?
For target as node, you might have to use this package webpack-node-externals in order to ignore all modules in node_module folder. Then declare as externals:
const nodeExternals = require('webpack-node-externals');
module.exports = {
externals: [nodeExternals()],
// ...
};
Although I am using vue-cli in the example code to generate a webpack config, nothing is specific to vue.
I create the example app like this:
vue init webpack webpack_modules_example
Generated webpack.base.conf:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'ad-block': 'ad-block/build/Release/ad-block.node',
'#': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
},
]
},
node: {
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
I want to include this library, so I do this:
npm install --save ad-block
And on the code (App.vue) I add this:
<script>
...
const {AdBlockClient, FilterOptions} = require('ad-block')
...
Because it's a native module, I need to install some loader for webpack (tried several):
npm install native-ext-loader --save-dev
Add the loader to the webpack config:
{
test: /\.node$/,
loader: "native-ext-loader"
},
And create an alias in the webpack config too:
alias: {
...
'ad-block': 'ad-block/build/Release/ad-block.node',
...
}
But when I run npm run dev and go to http://localhost:8080/
I see this error in the console:
Uncaught Error: Cannot open /ad-block.node: TypeError: Cannot read property 'dlopen' of undefined
at Object.eval (ad-block.node?9538:1)
at eval (ad-block.node:2)
at Object../node_modules/ad-block/build/Release/ad-block.node (app.js:733)
at webpack_require (app.js:679)
at fn (app.js:89)
at eval (App.vue?26cd:9)
at Object../node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue (app.js:757)
at webpack_require (app.js:679)
at fn (app.js:89)
at eval (App.vue?a8e9:1)
If I use this without webpack, it works. Not sure what am I missing!
NodeJS is a server-side programming environment and as such, supports “native” add-on modules compiled to run on the same host that runs your Node service.
While Node is programmed using JavaScript, it is not browser JavaScript and so native ad-ons cannot be expected to run in the browser.
See Node C++ Addons for more information.
I am using firebase in my react app. I only use the firebase/app and firebase/database modules, so I want webpack to bundle only what I used. However, webpack bundles everything in the firebase module. I cannot figure out how to tell webpack to ignore other modules.
I thought my issue was
import * as firebase from 'firebase';
However, I tried to import only bits and pieces of firebase.
import firebase from 'firebase/app';
import firebase from 'firebase/database';
but, webpack still bundles up auth.js and other unused modules.
Here is my webpack config file.
const path = require('path');
const webpack = require('webpack');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
cache: true,
entry: {
main: "./src/swap.tsx",
vendor: [
'babel-polyfill',
'events',
'fbemitter',
'flux',
'react',
'react-dom'
]
},
output: {
filename: "[name].js",
path: __dirname + "/app/assets/javascripts",
chunkFilename: '[chunkhash].js'
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
modules: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules')
]
},
module: {
rules: [{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{ loader: 'awesome-typescript-loader' }
]
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.js'
}),
new webpack.optimize.UglifyJsPlugin(),
new LodashModuleReplacementPlugin(),
new BundleAnalyzerPlugin(),
]
};
Add firebase/app and firebase/database to your vendor bundle array
I'm trying to setup Webpack to generate 2 bundles, one for server code with server side rendering and one for client code. So far the bundle seems to generate correctly but when I run the server code and it tries to render some of my React components it throws errors like this one:
ERROR in ./~/react-load-script/lib/index.js
Module build failed: ReferenceError: Unknown plugin "add-module-exports" specified in "/Users/alex/Development/muub/one/website/node_modules/react-load-script/.babelrc" at 0, attempted to resolve relative to "/Users/alex/Development/muub/one/website/node_modules/react-load-script"
at /Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
at Array.map (native)
at Function.normalisePlugins (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
at OptionManager.mergeOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
at OptionManager.init (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
at File.initOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:212:65)
at new File (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:135:24)
at Pipeline.transform (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
at transpile (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:46:20)
at Object.module.exports (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:163:20)
# ./App/Containers/Publish/Payment/Payment.jsx 18:0-39
# ./App/Containers/Publish/Payment/index.js
# ./App/Containers/Publish/Publish.jsx
# ./App/Containers/Publish/index.js
# ./App/Routes/index.js
# ./App/Containers/App.jsx
# ./App/index.js
# multi webpack-hot-middleware/client react-hot-loader/patch ./App
There are more errors similar to this one but related with other 3rd party npm packages.
Here is my webpack server config:
const path = require('path');
const webpack = require('webpack');
const ExternalsPlugin = require('webpack2-externals-plugin');
let conf = {
devtool: 'source-map',
context: path.resolve(__dirname),
entry: [
path.resolve(__dirname, 'index.js')
],
target: 'node',
output: {
path: path.join(__dirname, 'build'),
pathinfo: true,
filename: 'server.js',
publicPath: '/public/',
libraryTarget: 'commonjs2'
},
resolve: {
modules: ['App', 'node_modules'],
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'css-loader/locals',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
'postcss-loader'
]
},
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExternalsPlugin({
type: 'commonjs2',
include: path.join(__dirname, 'node_modules'),
exclude: [path.join(__dirname, 'node_modules', 'webpack/buildin'), path.join(__dirname, 'App')]
}),
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
}
module.exports = conf;
What could I be doing wrong?
I was reading all this week about this issue, but any of the solutions that are in the web doesn't work with the project that I am developing. I am working in a webapp using react and its related technologies. To make the compile process I am using the new version of webpack (v2.3.2). I have my server webpack configuration separate from my client webpack configuration. All were working good until I add socket.io in order to make some real-time components. Applying all the solutions that are in the web I am still get the following warning when I run my bundle script:
WARNING in ./~/express/lib/view.js
80:29-41 Critical dependency: the request of a dependency is an expression
WARNING in ./~/socket.io/lib/index.js
109:11-32 Critical dependency: the request of a dependency is an expression
WARNING in ./~/engine.io/lib/server.js
115:15-37 Critical dependency: the request of a dependency is an expression
And when I try to start my project, I get the following error:
return /*require.resolve*/(!(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
^
Error: Cannot find module "."
at webpackMissingModule (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:357017:76)
at Server.serveClient (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:357020:25)
at new Server (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:356959:8)
at Server (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:356951:41)
at Object.<anonymous> (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:72569:33)
at __webpack_require__ (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:20:30)
at Object.<anonymous> (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:344445:18)
at __webpack_require__ (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:20:30)
at /Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:66:18
at Object.<anonymous> (/Users/macpro/Documents/lisa_project/pos_lisa/built/server/index.js:69:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Here is my webpack.client.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['babel-polyfill', path.join(__dirname, '../source/client.jsx')],
output: {
filename: 'app.js',
path: path.join(__dirname, '../built/statics'),
},
module: {
rules: [
{
test: /\.json$/,
use: 'json-loader',
},
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2016', 'es2017', 'react'],
plugins: ['transform-es2015-modules-commonjs'],
},
},
{
test: /\.css$/,
exclude: /(node_modules)/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?modules',
}),
},
{
test: /\.inline.svg$/,
loader: 'babel-loader!react-svg-loader?' + JSON.stringify({
svgo: {
// svgo options
plugins: [{removeTitle: false}],
floatPrecision: 2
}
}),
},
{
test: /\.jpe?g$|\.gif$|\.png$|^(?!.*\.inline\.svg$).*\.svg$/,
loader: 'url-loader?limit=400000'
},
],
noParse: [ path.join(__dirname, '../node_modules/ws') ],
},
externals: [ path.join(__dirname, '../node_modules/ws'), path.join(__dirname, '../node_modules/socket.io') ],
target: 'web',
resolve: {
extensions: ['.js', '.jsx', '.css', '.json'],
},
plugins: [
new webpack.DefinePlugin({
'process.env.BROWSER': true,
}),
new ExtractTextPlugin({
filename: '../statics/styles.css',
ignoreOrder: true,
}),
],
watch: true,
};
Here is my webpack.server.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['babel-polyfill', path.join(__dirname, '../source/server.jsx')],
output: {
filename: 'index.js',
path: path.join(__dirname, '../built/server'),
},
module: {
rules: [
{
test: /\.json$/,
use: 'json-loader',
},
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['latest-minimal', 'react'],
},
},
{
test: /\.css$/,
exclude: /(node_modules)/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?modules',
}),
},
{
test: /\.inline.svg$/,
loaders: [ 'babel-loader',
{
loader: 'react-svg-loader',
query: {
svgo: {
plugins: [{removeTitle: false}],
floatPrecision: 2
}
}
}
]
},
{
test: /\.jpe?g$|\.gif$|\.png$|^(?!.*\.inline\.svg$).*\.svg$/,
loader: 'url-loader?limit=400000'
},
],
noParse: [ path.join(__dirname, '../node_modules/ws') ],
},
externals: [ path.join(__dirname, '../node_modules/ws'), path.join(__dirname, '../node_modules/socket.io') ],
target: 'node',
resolve: {
extensions: ['.js', '.jsx', '.css', '.json'],
},
plugins: [
new webpack.DefinePlugin({
'process.env.BROWSER': false,
}),
new ExtractTextPlugin({
filename: '../statics/styles.css',
ignoreOrder: true,
}),
],
watch: true,
};
And my server.jsx (the important parts)
import http from 'http';
import express from 'express';
import socketio from 'socket.io';
const lisaApp = express();
const server = http.createServer(lisaApp);
const io = socketio(server);
In advance, thanks for your help and answers
Well, I found the solution, maybe it helps someone else. In the server side configuration with webpack we have to read the list of directories inside node_modules and give to externals, keeping the "require" of our modules, so we have to add the following to our server side config. (Only the server side, the client side webpack works fine):
const fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
This code must be between const webpack and module.exports. And just after "module" object, add the following line:
externals: nodeModules,
Hope this helps to somebody.