Webpack - Getting node modules Into Bundle and loading into html file - javascript

I am trying to use node_modules in the browser via WebPack. I've read the tutorial and beginning steps but am stuck.
I have used webpack to generate bundle.js with the webpack config below and upon going to my index.html in Chrome browser I get the error:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (bundle.js:205)
What additional steps do I have to do to get the browser to recongnize require?
index.html
<script src="bundle.js"></script>
<button onclick="EntryPoint.check()">Check</button>
index.js
const SpellChecker = require('spellchecker');
module.exports = {
check: function() {
alert(SpellChecker.isMisspelled('keng'));
}
};
package.json
{
"name": "browser-spelling",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"node-loader": "^0.6.0",
"spellchecker": "^3.3.1",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: './index.js',
target: 'node',
output: {
path: './',
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
loaders: [
{
test: /\.node$/,
loader: 'node-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};

In your webpack.config.js you specified that you want to build this bundle for Node.js:
target: 'node',
And webpack decided to keep require calls, because Node.js supports them. If you want to run it in a browser, you should use target: 'web' instead.

In the new "webpack": "^5.75.0", Required has been changed to rules
webpack.config.js
const path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./index.js",
target: "node",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
{
test: /\.js$/,
exclude: /node_modules/,
},
],
},
};
package.json
{
"name": "arrybsc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^5.2.3",
"lodash": "^4.17.21"
},
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}

Related

Exclude in webpack-obfuscator does not work

We have implemented the obfuscator as per https://github.com/javascript-obfuscator/webpack-obfuscator.
We have only three subfolders in our project under the root: node_modules, src, dist. We expect these to all be non-obfuscated with the appropriate exclude in plugin, so the subsequent code in the bundle is not obfuscated at all. (This is, of course, just an intermediate step to make sure the exclude works at all. In the end, we just want to exclude node_modules from obfuscation).
The versions javascript-obfuscator (4.0.0) and webpack-obfuscator (3.5.1) are both the latest and should therefore be compatible?!
package.json
{
"name": "metrolyzer_npm",
"version": "1.0.0",
"description": "includes information about all modules required for the Metrolyzer",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"repository": {
"type": "git",
"url": "https://git.jetbrains.space/else42/metro/metrolyzer.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"autoprefixer": "^10.4.13",
"bootstrap": "5.0.2",
"css-loader": "^6.7.2",
"d3": "^7.7.0",
"dat.gui": "0.7.7",
"javascript-obfuscator": "^4.0.0",
"jquery": "3.6.0",
"postcss-loader": "^7.0.2",
"sass": "^1.56.1",
"sass-loader": "^13.2.0",
"style-loader": "^3.3.1",
"three": "0.123.0",
"three-orbit-controls": "^82.1.0",
"three.meshline": "^1.4.0",
"troika-three-text": "0.45.1",
"xlsx": "0.10.8"
},
"keywords": [],
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1",
"webpack-obfuscator": "^3.5.1"
}
}
webpack.config.js
const path = require('path');
var WebpackObfuscator = require('webpack-obfuscator');
module.exports = {
mode: 'production',
entry: {
index: './src/index.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '',
sourceMapFilename: "[name].js.map" // Allows us to get more detailed information about the source of an error
},
devtool: "source-map", // Allows us to get more detailed information about the source of an error
optimization: {
minimize: false, // Minimization should enabled for production
},
plugins: [
new WebpackObfuscator({rotateStringArray: true}, ['*node_modules*','*src*','*dist*'])
],
module: {
rules: [
{
test: /\.(sass|css)$/,
use: [ // The use of a loader is required because we are using .css from bootstrap
'style-loader',
'css-loader',
]
},
{
test: /\.js$/,
exclude: [
path.resolve(__dirname, 'node_modules')
],
enforce: 'post',
use: {
loader: WebpackObfuscator.loader,
options: {
rotateStringArray: true
}
}
}
]
}
};
Update: We were able to reproduce and resolve the problem. Two things had to be changed in order to make the exclusion of folders/files work.
Removing the line: new WebpackObfuscator({rotateStringArray: true}, ['*node_modules*','*src*','*dist*']) from the variable plugins. We suspect this to be redundant.
Use path.join() instead of path.resolve() when specifying which folders/files should be excluded. path.resolve() was resulting in C:\node_modules rather than C:\Users\ ... \ ... \ ... \node_modules\
After implementing these changes our issue was resolved. Below is the resulting webpack.config.js. Changes to the config other than the ones described in 1. and 2. can be ignored.
webpack.config.js
const path = require('path');
const WebpackObfuscator = require('webpack-obfuscator');
module.exports = {
mode: 'production',
entry: {
index: './src/index.js',
},
resolve: {
fallback: {
"stream": require.resolve("stream-browserify"),
"buffer": require.resolve("buffer")
}
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '',
sourceMapFilename: "[name].js.map"
},
devtool: "source-map",
optimization: {
//minimize: true,
module: {
rules: [
{ test: /\.(js|mjs)$/,
exclude: [
path.join(__dirname, '/node_modules/'),
path.join(__dirname, '/src/example/gui.js'),
],
enforce: 'post',
use: {
loader: WebpackObfuscator.loader,
options: {
reservedStrings: [ '\s*' ],
rotateStringArray: true,
identifierNamesGenerator: 'mangled-shuffled',
}
}
},
{ test: /\.(sass|css)$/,
use: [
'style-loader',
'css-loader',
]
}
]
}
};

Webpack dev server reloads but doesn't show Markup or CSS changes?

So i'm pretty new to Webpack, and I finally got the webpack-dev-server running. It recompiles and refreshes page on save, and it shows changes to my JS code. But it doesn't seem to work well with my SASS or HTML files?
On a fresh start, it will show a change if I make it, but if I undo that change, it doesn't update. Looking around other posts, I tried added the "--hot" flag, and adding "inline" to my devServer in webpack config. This got it working for a style change, but won't show deleted or undone changes.
This is my package.json...
{
"name": "testproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js",
"start": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js",
"watch": "webpack --watch",
"server": "webpack-dev-server --open --hot"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"autoprefixer": "^9.7.4",
"babel-loader": "^8.0.6",
"css-loader": "^3.4.2",
"cssnano": "^4.1.10",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"postcss-loader": "^3.0.0",
"sass": "^1.25.0",
"sass-loader": "^8.0.2",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.3"
}
}
This is my webpack.config...
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const isDevelopment = process.env.NODE_ENV !== 'production';
const webpack = require('webpack');
module.exports = {
entry: './src/javascript/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new MiniCssExtractPlugin({
filename: 'bundle.css'
}),
new HtmlWebPackPlugin({
template: './dist/index.html',
filename: 'index.html'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
inline: true,
hot: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader',
options: {
implementation: require('sass')
}
}
]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images'
}
}
]
},
{
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts'
}
}
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: !isDevelopment }
}
]
}
]
},
// Default mode is Production. Uses minifying
mode: 'development'
};
I must have something wrong or out of place?
Any help or tips would be appreciated. Will provide additional info if needed.
Thanks in advance!
I found a solution by adding "watchContentBase" to my devServer.
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
**watchContentBase: true,**
inline: true,
hot: true
}

webpack autobuild/auto serve application

i am using this webpack project template from here
to run it i use npm run serve .how can I add auto build/serve when files are changed. is it something to do with webpack or npm? .i am new to this javascript tooling & searching on google gives lots of options which is overloaded with information & configurations each different.
attaching the webpack config:
const path = require('path')
const webpack = require('webpack')
module.exports = env => {
return {
entry: {
main: './src/index.js'
},
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: "/"
},
mode: env && env.production ? 'production' : 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: [/\.vert$/, /\.frag$/],
use: 'raw-loader'
}
]
},
devServer
: {
contentBase: './dist'
},
plugins: [
new webpack.DefinePlugin({
'CANVAS_RENDERER': JSON.stringify(true),
'WEBGL_RENDERER': JSON.stringify(true)
})
]
}
}
my package.json file:
{
"name": "phaser3-webpack",
"version": "1.0.0",
"description": "A basic Phaser 3 starter project",
"main": "index.js",
"scripts": {
"build": "webpack",
"build:production": "webpack --env.production",
"clean": "rimraf dist/bundle.js",
"watch": "webpack --watch",
"serve": "webpack-dev-server"
},
"keywords": [
"phaser",
"webpack",
"es6"
],
"author": "John Cheesman",
"license": "MIT",
"dependencies": {
"phaser": "^3.1.2"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"raw-loader": "^0.5.1",
"rimraf": "^2.6.1",
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"webpack-dev-server": "^3.0.0"
}
}

Error: `output.path` needs to be an absolute path or `/` [duplicate]

This question already has answers here:
Getting "Error: `output.path` needs to be an absolute path or `/`"
(5 answers)
Closed 5 years ago.
I am a beginner in React,and at the moment I am trying to do the basic set up. So far I installed the basic modules from npm and the folder structure of my project is as shown below.
The package.json shows what I have installed as well as a small description of the project.
{
"name": "test",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"repository": {
"type": "git",
"url": "https://github.com/theo82"
},
"keywords": [
"test"
],
"author": "Theo Tziomakas",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.1"
}
}
Anyway when I am typing npm start,I get this error.
Error: `output.path` needs to be an absolute path or `/`.
at Object.setFs (C:\Users\Theodosios\Desktop\reactApp\node_modules\webpack-d
ev-middleware\lib\Shared.js:88:11)
I believe this has to do with the webpack.config.js file.
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 3000
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
How can this error be fixed?
Thanks,
Theo?
you need to define the output path relative to webpack config.
path: path.resolve(__dirname, './'),
publicPath: '/',
filename: 'bundle.js'

Webpack isn't excluding node_modules

I have the following directory structure:
- webpack.config.js
- src
- index.js
-dist
- index.js
A webpack config:
module.exports = {
module: {
loaders: [{
test: /\.js$/,
include: __dirname + 'src',
exclude: __dirname + 'node_modules',
loader: "babel-loader"
}],
},
resolve: {
extensions: ['.js']
},
output: {
path: __dirname + '/dist',
filename: 'index.js'
}
};
But if I import request in my src/index.js (const request = require('request');) I'm getting errors from node_modules.
How can I avoid this? I've thought I've excluded node_modules.
Just for completion my package.json:
{
"name": "leo-trans",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch",
"start": "node dist/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"preferGlobal": true,
"bin": {
"leo-trans": "./dist/index.js"
},
"devDependencies": {
"babel-core": "^6.3.26",
"babel-loader": "^6.2.1"
},
"dependencies": {
"cheerio": "^0.19.0",
"request": "^2.67.0"
}
}
You've not excluded node_modules, because __dirname doesn't contain trailing slash. Try to use path.resolve:
const path = require('path');
module.exports = {
module: {
loaders: [{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: path.resolve(__dirname, 'node_modules'),
loader: "babel-loader"
}],
},
// ...
}

Categories