Webpack itself is working fine, but the webpack-dev-server is not. Basically, webpack created 2 build files for me, a back-end bundle and a front-end bundle. So, I have a webpack-config.js for each of these. I want to develop my front-end code with webpack-dev-server, as you can see from my webpack-config file for my front-end-bundle.js below. When I run web-pack-dev server, it is able to find and build my front-end.js and index.html, but nothing renders in the console and it gives me a "Uncaught ReferenceError: require is not defined"
// var nodeExternals = require('webpack-node-externals');
var webpack = require('webpack');
module.exports = {
entry: './browser/entry.js',
output: {
path: './builds',
filename: 'frontend.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"development"'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"development"'
}
})
],
module: {
loaders: [
{
test: [/\.es6$/, /\.js$/, /\.jsx$/],
exclude: 'node_modules',
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.html$/,
loader: 'html-loader'
},
]
},
resolve: {
extensions: ['', '.js', '.es6', '.json'],
root: '/Users/johnhenry/Desktop/GAMR/gamr/browser'
},
devServer: {
contentBase: 'builds/dev-build'
},
target: 'node',
// externals: [nodeExternals()]
}
The error is triggered by this in my front-end build (it is only in the dev server build, not in the non-dev-server webpack build):
function(module, exports) {
module.exports = require("url");
If anyone has insight into this, it would be much appreciated
Try adding:
target: 'web'
to your module block.
I had the same error and if anyone is still struggling with this, this solution also helped me:
... There are 2 ways to solve the issue:
1. (Recommended) Don't activate webpack-node-externals in your Webpack browser config, but let Webpack indeed bundle those modules
when targeting the web (this is probable what you want to do)
Have the external modules loaded in some other way in the browser, and add the appropriate importType flag to the webpack-node-externals configuration (either var for scripts or amd for AMD)
more details here: https://github.com/liady/webpack-node-externals/issues/17#issuecomment-284222729
I hit this issue when a webpack.config.js from a node app for the base of a react app.
I had the following:
target: 'web'
but still ran in to the same issue.
Removing reference to webpack-node-externals solved it, which does make sense when you think about what node-externals is actually doing.
I had below rule in my webpack.config.js
rules: [
{
test: /\.js$/,
use:['script-loader']
}
]
Removing above rule from webpack.config.js removed the error.
Hope this helps.
Related
my typescript file includes the following import:
import { SPComponentLoader } from '#microsoft/sp-loader';
But I get a lot of errors when building with webpack
npx webpack --config webpack.config.js
Here are some of the errors:
ERROR in
./node_modules/#microsoft/sp-loader/lib/requirejs/RequireJsLoader.js
Module not found: Error: Can't resolve './test/RequireJsMock' in
'C:\users\agaskell\source\repos\spfxBanner\node_modules#microsoft\sp-loader\lib\requirejs'
# ./node_modules/#microsoft/sp-loader/lib/requirejs/RequireJsLoader.js
258:14-45 #
./node_modules/#microsoft/sp-loader/lib/requirejs/SPRequireJsComponentLoader.js
# ./node_modules/#microsoft/sp-loader/lib/starter/SPStarter.js #
./node_modules/#microsoft/sp-loader/lib/index.js #
./Classic/client/bootHeader.ts # multi #babel/polyfill
./Classic/client/bootHeader.ts
ERROR in
./node_modules/#microsoft/sp-loader/lib/systemjs/SystemJsLoader.js
Module not found: Error: Can't resolve './test/SystemJsMock' in
'C:\users\agaskell\source\repos\spfxBanner\node_modules#microsoft\sp-loader\lib\systemjs'
I am trying to build my ts file into js for classic SharePoint sites and I normally use gulp for modern pages, but for classic I am using a separate bootloader.ts file and webpack.
Can anyone help?
Here is the webpack.config.js file:
const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: "development",
entry: ['#babel/polyfill',
path.resolve(__dirname, './Classic/client/bootHeader.ts')],
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
},
{
test: /\.(s*)css$/,
use: [
// fallback to style-loader in development
process.env.NODE_ENV !== "production"
? "style-loader"
: MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [
{
loader: "url-loader",
options: {
limit: 15000, // Convert images < 8kb to base64 strings
name: "images/[hash]-[name].[ext]"
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
filename: "classicBundleAG.js",
path: path.resolve(__dirname, "Classic"),
libraryTarget: "umd"
}
};
I ended up using a workaround for this. I gave up on SPComponentLoader to load my bootstrap and instead installed bootstrap modules locally and then referenced them from my custom sass.
My thoughts are that gulp with yeoman normally handles the SPComponentLoader dependencies, but this time I am using a custom webpack and I did not want to deal with every missing dependency manually.
I have a NodeJS project that I'm building with Webpack and running inside a Docker container. This was being developed in a Linux environment, but I decided to try to move it to WSL (Windows subsystem for Linux) because that would make things easier for the dev team. Getting it to run on WSL has been difficult though.
Currently the project builds with no problems, and Docker also seems to be running smoothly. However, when I open the project on a browser, nothing loads. On the console is the following error message:
Uncaught TypeError: Cannot read property 'native' of undefined
at Object../node_modules/fs-extra/lib/fs/index.js (index.js:107)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/fs-extra/lib/index.js (index.js:6)
at __webpack_require__ (bootstrap:19)
at Object.<anonymous> (RollingFileWriteStream.js:2)
at Object../node_modules/streamroller/lib/RollingFileWriteStream.js (RollingFileWriteStream.js:265)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/streamroller/lib/index.js (index.js:2)
at __webpack_require__ (bootstrap:19)
at Object.<anonymous> (file.js:3)
When I check index.js:107, I see the following lines:
// fs.realpath.native only available in Node v9.2+
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
}
However, all node versions I have running are 10+. My base image is node:12 (more specifically, version 12.13.0). Nodejs and npm versions on WSL are:
me#computer:.../addin$ nodejs --version
v12.11.1
me#computer:.../addin$ npm --version
6.12.0
And NodeJS on windows is:
PS H:\> node --version
v10.15.3
I'm not sure if this is relevant, but here are my webpack config files:
webpack.server.config.js:
const path = require('path')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: {
server: './src/server/server.js',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
fs: 'empty'
},
externals: [nodeExternals()], // Need this to avoid error when working with Express
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
}
webpack.config.js:
const path = require("path")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
main: './src/js/index.tsx'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'web',
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.tsx', '.html', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: 'ts-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/html/index.html",
filename: "./index.html",
excludeChunks: [ 'server' ]
})
]
}
And the build command is:
rm -rf dist && webpack --mode development --display-error-details --config webpack.server.config.js && webpack --mode development
I'm out of ideas on how to fix this. I have tried removing and reinstalling nodejs, deleting all docker images, etc. Any suggestions would be much appreciated.
Fixed by installing this npm package, importing it on server.js, and monkey-wrenching:
var rp = require('fs.realpath')
rp.monkeypatch()
Unfortunately fixing it didn' give me any more insight on what's wrong with WSL and node, but at least it works.
EDIT:
Since this question seems to be relevant to some, I have since discovered that the real problem is that I was trying to use fs in a class that was bundled with target: 'web' (the second config file I posted). This is another part of the code, and it didn't occur to me that this could be the problem.
The webpack.config.js I posted originally is for an expressJS server, while this other part of the code was for the frontend of the application.
From what I understand, target: 'web' tells Webpack not to bundle and NodeJS functions because this code will be run in a browser. target: 'node' is appropriate for code that will run in a node environment (i.e. an expressJS server, that will run on the backend)
I hope this helps people who are running into this problem.
Do you have jquery in your package.json? I remember getting that error with Create-React-App when I forget to add the jquery cdn to index.html
I am working with a React project. Every time I make any change in any of the .js files, I have to run the "webpack" command in the terminal again to get the changes reflect on browser. Is there any way so that I cannot have to run the "webpack" command again n again.
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devServer: {
inline: true,
contentBase: './src',
port: 3000
},
devtool: 'cheap-module-eval-source-map',
entry: './dev/js/index.js',
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
output: {
path: 'src',
filename: 'js/bundle.min.js'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin()
]
};
You need webpack-dev-server and react hot loader, also you need development config. Please take a look at this page ReactHotLoader and if you find it complex comment here and i will provide you more links that could be helpful.
Also please take a look at this example Github:React-redux-app, this could help you set up your development env.
It's simple. Just run webpack with -w flag to make it watch for changes and rebuild every time on change.
webpack -w
I am using webpack+react+redux on a web application. And I am using webpack-dev-server to launch dev web server. When I access my application on a browser, it gives below error messages on the console:
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster.
You are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify to ensure you have the correct code for your production build.
Below is my webpack.config.js file. I didn't specify production mode, why webpack gives me such warning message? And how can I get rid of it?
const webpack = require('webpack');
const path = require('path');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
const PATHS = {
react: path.join(__dirname, 'node_modules/react/dist/react.min.js'),
app: path.join(__dirname, 'src'),
build: path.join(__dirname, './dist')
};
module.exports = {
entry: {
app: './app/index.jsx',
android: './app/utils/platform_android.js',
ios: './app/utils/platform_ios.js',
web: './app/utils/platform_web.js',
vendor: [
'axios',
'react',
'react-dom',
'react-redux',
'react-router',
'react-router-redux',
'redux',
'redux-thunk',
'react-alert',
'sha1',
'moment',
'nuka-carousel',
'react-cookie',
'material-ui',
'react-spinkit',
'react-tap-event-plugin',
'react-tappable',
],
},
output: {
path: PATHS.build,
filename: '[name].bundle.js',
},
watch: true,
devtool: 'source-map',
relativeUrls: true,
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.less'],
modulesDirectories: ['node_modules'],
alias: {
normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
},
// {
// test: /\.js$/,
// exclude: /node_modules/,
// loader: 'jshint-loader'
// }
],
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?presets=es2015',
},
{
test: /\.less$/,
loader: "style!css!less",
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.png$/, loader: "url-loader?limit=100000"},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader?presets=es2015']
},
{
test: /\.svg$/,
loader: 'svg-sprite',
include: /public\/icons/
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new NpmInstallPlugin({
save: true // --save
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */["vendor"], /* filename= */"[name].bundle.js", Infinity),
],
devServer: {
colors: true,
contentBase: __dirname,
historyApiFallback: true,
hot: true,
inline: true,
port: 9093,
progress: true,
stats: {
cached: false
}
}
}
EDIT1:
I removed this line:
react: path.join(__dirname, 'node_modules/react/dist/react.min.js'),
Then updated the NODE_ENV to development as below:
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("development")
}
})
Then I still got the same warning.
warning.js:14You are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) to ensure you have the correct code for your production build.
I don't know how to say it more clear than webpack does...
You are not in a production build mode, but using a minified version of React. Use a non-minified one, so replace
react: path.join(__dirname, 'node_modules/react/dist/react.min.js'),
with
react: path.join(__dirname, 'node_modules/react/dist/react.js'),
or whatever place where you have your react not minified.
And this is not an error - it is a warning, so you can still work with this one.
Just another thing by the way: path.join adds proper slashes for each operating system. What you do here is
path.join(__dirname, 'node_modules/react/dist/react.min.js')
when you should go with
path.join(__dirname, 'node_modules', 'react', 'dist', 'react.min.js')
This is how the path should be properly used
The warning you get now is because you are letting Webpack minify your build, but you are still setting NODE_ENV to development.
If you use UglifyJsPlugin you should always set NODE_ENV to production. If you're not building for production, remove UglifyJsPlugin to not get any warnings.
Webpack, React and Redux try to give you some best practice hints here. In development mode (NODE_ENV not set to production), they all give more warnings and have lower performance. When you minify them they assume you're running a production build. For production builds, they really expect NODE_ENV to be set correctly.
So in short:
Production builds: set NODE_ENV to production and use UglifyJsPlugin.
Dev builds: set NODE_ENV to development and don't use any minification plugins.
I fixed it by removing below configuration from webpack.config.js for development build. It seems that this plugin will compress the js code which is not suitable for development mode.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
})
I am currently building an electron app to deploy on a raspberry pi3 with a react front end. It's using webpack to bundle everything. I am also trying to use the node-raspicam package to interact with the camera module. I have successfully been able to use the node-raspbicam package on it's own outside of this app. But when I try to import it in this application I get the following error
Module not found: Error: Cannot resolve 'file' or 'directory' ../options in /usr/src/app/node_modules/raspicam/lib
# ./~/raspicam/lib/raspicam.js 7:17-38 8:12-33
in raspicam.js it tries to do parameters = require("../options").parameters which is where it is failing.
In the raspicam tree within node_modules options.json exists one directory up from where it is being called.
My thought is webpack is not bundling this json file properly therefore, it cannot be found.
My webpack loaders :
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
},
{
test: /\.(jpg|png)$/,
loader: 'file?name=[path][name].[hash].[ext]',
include: path.images
},
{
test: /\.json$/,
loader: 'json-loader'
}]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'commonjs2'
},
resolve: {
extensions: ['', '.js', '.jsx'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
},
plugins: [
],
externals: [
// put your node 3rd party libraries which can't be built with webpack here
// (mysql, mongodb, and so on..)
]
I am still fairly new to webpack. What am I missing so that the options.json file in the raspicam node_module gets bundled properly?
Try adding .json to the extensions in the resolve object in the config file. It may work.