Webpack/Javascript - Browser keeps refreshing when I do "npm run build-dev" - javascript

I am trying to get more familiar with using webpack. I have converted everything to be able to load modules, and plugins. Everything loads fine when I run "npm run build-prod", when I use liveServer, HTML and everything loads properly. However when I run "npm run build-dev", it auto pops up my index.html file and starts reloading the page nonstop, and doesn't apply any CSS. The reloading issue makes me think I am using npm run build-dev wrong.
I am pretty new to webpacks, but to my understanding, the point of running "npm run build-dev", it will compile everything using my loaders and plugins without minifying everything, so I can edit and make changes in real time. Or is my understanding completely wrong.
const path = require("path");
const webpack = require("webpack");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./src/client/index.js",
mode: "development",
devtool: "source-map",
stats: "verbose",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: "/.js$/",
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/client/views/index.html",
filename: "./index.html",
}),
new CleanWebpackPlugin({
// Simulate the removal of files
dry: true,
// Write Logs to Console
verbose: true,
// Automatically remove all unused webpack assets on rebuild
cleanStaleWebpackAssets: true,
protectWebpackAssets: false,
}),
],
};
Here is my full repo, but without the .env variables holding my API keys.

Just a friendly advice: It feels like you started doing something complex without getting the basics right.
Why don't you try some of the examples first?
The webpack website is quite rich of those: https://webpack.js.org/guides/getting-started/

Never figured out what the issue was, but when I ran it on my Mac instead of Windows, I couldn't reproduce the issue. I tried on both Chrome and FireFox without any plug-in.

Related

Webpack unexpected token react native

I'm trying to integrate a connection to Ledger nano X devices, into a native Swift package. Unfortunately Ledger only provide an SDK as a ReactNative module. I dislike ReactNative and really don't want to integrate it into my entire Swift package, and force it onto my users, just for this one library.
I've had limited success in the past converting NodeModules into plain .js files that I can run directly with iOS's JavascriptContext. I've used webpack to bundle it up into a single plain js file (no require, import, export etc keywords). Adding a native Swift wrapper around that lets me keep all the messy dev setup and tools out of my project and just leverage the plain JS when needed for small use-cases. I've very little experience with this and what i've done in the past isn't working, hours of googling hasn't gotten me any closer.
Building the entire Ledgerjs with webpack was throwing up errors, since I only need pieces of it I started trying to get one of the sub-packages #ledgerhq/react-native-hw-transport-ble to build. I forked the project and added this webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
"ledger_transport_ble": ['./src/awaitsBleOn.ts', './src/BleTransport.ts', './src/monitorCharacteristic.ts', './src/remapErrors.ts', './src/timer.ts', './src/types.ts']
},
mode: 'production',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
modules: ['node_modules'],
fallback: {
"stream": require.resolve("stream-browserify")
}
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: ['[name]'],
libraryTarget: "var"
},
plugins: [
new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] })
],
};
with this .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-flow"
]
}
and I get back this error:
ERROR in ./node_modules/react-native-ble-plx/index.js 11:7
Module parse failed: Unexpected token (11:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export { State, LogLevel, ConnectionPriority, ScanCallbackType, ScanMode } from './src/TypeDefinition'
|
> export type {
| Subscription,
| DeviceId,
# ./src/BleTransport.ts 87:29-60
Instructions online where to add the .babelrc file that I added above, but it made no difference. Have I missed a step somewhere? Or is there something else I should be doing?

Trying to save configuration settings to a JSON file on a user's computer from the web browser using a React App that has webpack?

I am working on a social media app for a friend at their request which should allow them to create categories and then write hashtags that correspond to those categories. Afterwards they can just select them as opposed to spending the time typing them all out every single time.
Given the constant updating nature of the project I had set myself for a react web-app and thought I could store the categories and hashtags made in a .JSON file and then any time they added a new category / hashtag, I could just write to that .JSON file.
problem is, using "fs" gets me this error Cannot find module "fs" and the solutions about externals or target Node or other methods invariably results in Uncaught ReferenceError: require is not defined on the .JSX file that makes the reference to fs
I have linked my webpack below. I want to save to a .JSON file on the local computer's file system so I do not have to deal with/pay for some sort of online storage space. I do not want to use the download command because I do not want to open up that dialogue box and would rather have the file be written to a static location in the background. Likewise, I thought a webpage would be a good way to implement the app because when it is built they can just download from github and open the index.html in their preferred browser. If there is another alternative which is less of a headache I am all for listening to suggestions.
var path = require('path')
const mode = process.env.NODE_ENV
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack')
module.exports = {
mode: 'development',
entry: path.join(__dirname,'./index.js'),
output:{
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
devServer:{
publicPath: '/build/',
port:8080,
hot: true,
},
plugins: [ new MiniCssExtractPlugin(), new webpack.HotModuleReplacementPlugin() ],
module:{
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env','#babel/preset-react']
}
}
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
//'style-loader',
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
}
]
}
}
edited for additional clarity

Webpack is importing modules from my machine's global `node_modules`. How do I get it to only import from my project's `node_modules`?

I'm migrating a project from using Grunt to using Webpack. This project uses jQuery. I noticed that the bundled code was working fine, even though I hadn't yet added jQuery to package.json, which seemed strange.
Looking at the output of webpack --mode=development --display-modules, I saw:
[../../../../../../../node_modules/jquery/dist/jquery.js] /Users/rothomas/node_modules/jquery/dist/jquery.js 274 KiB {index} [built]
That is: it seems at some point I ran npm install --global jquery, and Webpack is importing that jQuery. I don't want this to happen, because my teammates/server won't have jQuery installed in $HOME.
The obvious solution is for me to just remove jQuery from my $HOME/node_modules (no idea how it got there anyway), which will cause Webpack to fail until I add it to package.json, as expected.
But I'd like to know:
Why does Webpack use $HOME/node_modules? I understand this is the default behavior of Node package resolvers, but it seems very error-prone since I imagine many other developers keep their projects nested under $HOME.
How can I specify the scope within which Webpack should be trying to resolve modules?
(I looked at Webpack's documentation on resolvers, but it's not very clear to me.)
Here is my current Webpack config:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
function pathTo(filepath) {
return path.join(__dirname, filepath);
}
module.exports = function (env, argv) {
return {
entry: {
'index': [
pathTo('src/scripts/index.js'),
pathTo('src/scss/index.scss'),
]
},
module: {
rules: [
{
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
'#babel/env'
]
},
test: /\.js$/,
},
{
test: /\.(scss|css|sass)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
url: false,
},
},
{
loader: 'sass-loader',
options: {
sassOptions: {
outputStyle: 'expanded',
},
},
},
],
},
],
},
output: {
filename: '[name].js',
path: pathTo('web'),
},
plugins: [
new MiniCssExtractPlugin()
],
}
}
The problem is that your app is located inside the directory that has your global node_modules directory.
Webpack (and for that matter all node resolvers) will keep searching up your tree until it finds a directory that has a node-modules directory. then it will check in there for jquery. It continues doing this until it either finds what it's looking for, or if it reaches the root of your filesystem.

webpack configuration webpack-dev-server does not compile files on the fly

I have following webpack configuration file.
const path = require('path');
const webpack = require('webpack');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'scripts.min.js'
},
resolve: {
root: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
entry: './src/app.js',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel'
}
]
},
devServer: {
// compress: true,
inline: true,
stats: 'errors-only'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ 'mangle': false, sourcemap: false })
]
};
The problem is that when I run webpack-dev-server command, it does run the server but when I make changes to any js file they are not compiled on the fly. So I had to stop the server and run webpack and then run webpack-dev-server command to make things work.
How can I make webpack-dev-server work so that when watches for all js, css, scss files and compile those fly?
If you are working with an IDE, you have to disable "safe write".
Note that many editors support “safe write” feature and have it enabled by default, which makes dev server unable to watch files correctly. “Safe write” means changes are not written directly to original file but to temporary one instead, which is renamed and replaces original file when save operation is completed successfully. This behaviour causes file watcher to lose the track because the original file is removed. In order to prevent this issue, you have to disable “safe write” feature in your editor.
http://webpack.github.io/docs/webpack-dev-server.html#hot-mode

npm link with webpack - cannot find module

I'm trying to npm link a module to a project using webpack as its bundler. Of course, after trying many things, I keep getting this error:
ERROR in ./src/components/store/TableView.jsx
Module not found: Error: Cannot resolve module 'react-bootstrap-table'
Here are the exact steps I take when doing this:
1.) cd ../forks/react-bootstrap-table
2.) npm link
(success, checked ~/.nvm/.../node_modules/react-bootstrap-table for symlink and it's there)
3.) cd ../../projRoot/
4.) npm link react-bootstrap-table
(no errors thrown?, says successful link)
5.) node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
Solutions I've tried:
- https://webpack.github.io/docs/troubleshooting.html
- How to make a linked component peerDepdencies use the equivalent node_modules of the script being linked to?
- And many purple links on google serps
webpack.config.js
const webpack = require('webpack')
const path = require('path')
const ROOT_PATH = path.resolve(__dirname)
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? '' : 'source-map',
entry: [
'webpack/hot/only-dev-server',
'./src/index.js'
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot','babel']
},
{
test: /\.scss$/,
loaders: ['style','css','sass'],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style','css']
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
fallback: path.resolve(__dirname, './node_modules')
},
resolveLoader: {
fallback: path.resolve(__dirname, './node_modules')
},
output: {
path: process.env.NODE_ENV === 'production' ? path.resolve(ROOT_PATH, 'app/dist') : path.resolve(ROOT_PATH, 'app/build'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(ROOT_PATH),
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
stats: 'errors-only',
host: '192.168.1.115'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
Notes:
1. this is the only symlink in the project
2. I run npm install inside forked version (also tried without, doesn't work)
3. I use NVM, but I have used symlinks before without webpack successfully.
I've been at this for a few days now, any help will be much appreciated.
I was facing a similar issue with webpack and ended up by adding this my webpack.config.js:
module.exports = {
resolve: {
symlinks: false
}
};
Here is the link to webpack docs. Since your question there happened a lot to webpack and their api, so I do not know how much relevance my answer still has according to your question. But for people facing this or a similar issue today this could be a solution. As to be seen, there are still people complaining about:
Webpack GitHub Issue 1643
Webpack GitHub Issue 1866
Also make sure you have bundle and yarn installed and executed in the linked package
Okay guys, this is specific to my use case, but make sure to follow all the instructions to completely build the library you are symlinking. Initially, I a npm install and gulp build, but that wasn't enough. I had to run a few extra commands to get the library to fully build.
Now it works! If you are still having issues, go through the documentation for each library you are symlinking, and use my webpack config as a template for resolving external libraries.
Just in case it's useful for others, the solution of adding the resolve.symlinks configuration to false suggested by #Beat was not enough in my case, I had to perform the following steps to solve it:
In the library:
Setup the libraries that are generating issues as peerDependencies in the package.json instead of dependencies or devDependencies, e.g. in my case react:
"peerDependencies": {
"react": "^16.8.6",
...
}
run npm install
build the library (in my case, with a rollup -c npm script
In my main app:
change the version of my library to point to my local project with a relative path in package.json, e.g.
"dependencies": {
"my-library": "file:../../libraries/my-library",
...
}
Add resolve.symlinks = false to my main app's webpack configuration
Add --preserve-symlinks-main and --preserve-symlinks to my package.json start script, e.g:
"scripts": {
"build": "set WEBPACK_CONFIG_FILE=all&& webpack",
"start": "set WEBPACK_CONFIG_FILE=all&& webpack && node --preserve-symlinks-main --preserve-symlinks dist/server.js",
}
run npm install
run npm run start

Categories

Resources