Can't require webpack on webpack.config - javascript

I'm trying to start a webapp with three.js, and i want to use webpack for bundling everything together, but i can't seem to figure out to require("webpack") on the webpak.config, i have to do this in order to use the webpack.providePlugin
Here is my webpack.config.js
var path = __dirname;
const webpack = require('webpack');
module.exports = {
entry: {
main: './main.js'
},
output: {
path: __dirname + '/dist/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
And here's the error that appears when i run webpack
Error on webpack run
The error only appears when i try to require webpack

I'm 99% sure the problem is that you're using an old version of Node.js.
Here's your error message:
/home/eloy/Sites/proyectomi/node_modules/webpack/lib/Compiler.js:10
const {
^
SyntaxError: Unexpected token {
If you're using Webpack 4.3 or 4.4 (the most current versions), then the line in question, line 10 of lib/Compiler.js, is the first line of this destructuring assignment:
const {
Tapable,
SyncHook,
SyncBailHook,
AsyncParallelHook,
AsyncSeriesHook
} = require("tapable");
A quick visit to node.green tells us that object destructuring wasn't supported in Node.js until version 6.4.0.
The webpack docs recommend using the current LTS release of Node.js:
Pre-requisites
Before we begin, make sure you have a fresh version of Node.js installed. The current Long Term Support (LTS) release is
an ideal starting point. You may run into a variety of issues with the
older versions as they may be missing functionality webpack and/or its
related packages require.
As of today (2018-03-30), that's Node.js 8.11.1.

1) var path = __dirname;
This line needs to be removed.
2) npm install webpack --save-dev
This will add webpack to dev dependencies.

Related

Access fs module in typescript and webpack [duplicate]

I'm using node.js and webpack to create a bundle. From what I've read, node.js should contain fs module for managing files. However when I call require("fs") I get an Cannot find module "fs" error. What should I do?
I came across this problem myself when bundling with webpack and found the answer on this thread.
The way to solve it for me was to use the following config:
module.exports = {
entry: "./app",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: 'node_modules',
loader: 'babel',
query: {presets: ['es2015']},
}
]
},
target: 'node'
};
By setting target to node webpack will make the necessary changes to bundle your node application
Edit: This answer targeted webpack 1.x which has now been superseded.
If you are running your webpack bundle in nodejs environment then target: 'node' is required in webpack.config.js file otherwise webpack takes default value as web for target check here.
You can resolve the issue in two ways
Add below configuration to your webpack.config.js
node: {
fs: "empty"
}
OR
Add below configuration to your package.json
"browser": {
"fs": false
}
Edit:
promising fix is
"browser": {
"fs": false
}
I had the same issue when bundling a NWjs application using webworkers (which in turn had node enabled).
The solution I found was to include each native module I used in externals with the prefix commonjs to the name of the module. For example:
...
target: "webworker", // or 'node' or 'node-webkit'
externals:{
fs: "commonjs fs",
path: "commonjs path"
}
...
I've done the same for targets "webworker" and "node-webkit" in different projects to solve the same issue.
webpack nwjs webworker nodejs node
Add below configuration to your webpack.config.js
resolve: {
fallback: {
fs: false
}
}
I needed to build a class that would use fetch if executed in a browser, or fs if executed in node. For other reasons, it was impractical to produce separate bundles, so I produced a single browser-targeted bundle.
The solution I used was to use eval('require("fs")') if the script was running in node.
const fs = eval('require("fs")')
Browser-safe (fs is null in the browser):
const fs = typeof window === 'object'
? null
: eval('require("fs")')
After trying everything I found on the internet (target, externals, node configs), the only solution that actually worked for me was replacing:
const filesystem = require("fs")
or
import fs from "fs"
by the special webpack version
const fs = __non_webpack_require__("fs")
This generates a require function that is not parsed by webpack.
In addition to the answer of PDG
I'm used to this short copy/paste candy.
Using path and fs :
var nodeModules = {};
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
.filter(x => ['.bin'].indexOf(x) === -1)
.forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });
// Before your webpack configuration
module.exports = {
...
}
Then inside your configuration file, include the nodeModules variable in the externals
...
externals: nodeModules,
...
It would be more elegant to use pre-defined solution as:
Adding target: 'node' to webpack config file.
More info on: official documentation
For the solution we are building we had to force an older version of webpack:
npm install --save --force webpack#webpack-3

Configure Webpack 4 with aliases, Babel 7 to build React components library

I'm trying to create two React projects:
React components library (only components without working application)
SPA application which uses created components (examples application)
I would like to achieve a folders structure like:
./src - directory with React components
./example - contains SPA app which uses ./src components
There are configuration files in example directory (simplest React + webpack config without HMR and other stuff):
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const aliases = require('./aliases.js');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
resolve: {
alias: aliases
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
aliases.js
var path = require('path');
module.exports = {
'webpack-alias-react': path.resolve(__dirname, '../src')
};
babel.rc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
VSCode alias config is in jsconfig.json file.
And there is my problem.
When ./src/SimpleComponent contains code like that:
const SimpleComponent = () => {
return 'string';
};
Running npm run build command builds working application.
But when ./src/SimpleComponent returns:
const SimpleComponent = () => {
return <div>abc</div>;
};
npm run buid command throws exception:
ERROR in ../src/SimpleComponent.js Module build failed (from
./node_modules/babel-loader/lib/index.js): SyntaxError:
D:\Tranzystor\webpack-alias-react\src\SimpleComponent.js: Unexpected
token (4:9)
How to solve this webpack/Babel configuration issue?
Why is it possible to write <div> in App.js?
Is that right approach?
Whole code is here available.
I've solved that issues with Babel 7 and extended solution for that kind of issues is there:
github
It's ready to use webpack 4 + React + Babel 7 + eslint configuration.
It can be helpful for monorepo solutions.
Publishing your own components library to npm can be another application. As I mentioned above ./src directory contains small react components (content which you want to publish on npm). In ./demo directory there is spa application which shows how to use supplied components (it can be storybook for example).

Webpack authoring libraries import errors with TypeError: xxx is not a constructor

I am having trouble importing a javascript package I wrote (and published to npm) into a new project.
I created an ES6 package and bundled it using webpack. Within the package I can import the library using the bundled file using a script tag,
<script src='../dist/awesome-table-dist.js'></script>
then new up the class like so:
let awesomeTable = new AwesomeTable.AwesomeTable('record');
Works like a charm! awesome-table
I pushed the package up to npm, now I want to bring it into a new project like so:
import AwesomeTable from '#iannazzi/awesome-table'
then
let awesomeTable = new AwesomeTable('record');
which is erroring:
TypeError: _iannazzi_awesome_table__WEBPACK_IMPORTED_MODULE_0___default.a is not a constructor
Now that I am importing it to a new project I have tried a variety of ways new up the class, but seem completely stuck.
I can use the package by including the script again, but obviously I want to import so I can re-package:
<script src='node_modules/#iannazzi/awesome-table/dist/awesome-table-dist.js'></script>
Here is the webpack configuration for the package:
var path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const SRC_DIR = path.resolve(__dirname,'../src');
const DIST_DIR = path.resolve(__dirname, '../dist');
module.exports = {
entry: {
app: SRC_DIR + '/table/AwesomeTable.js'
},
output: {
path: DIST_DIR,
filename: 'awesome-table-dist.js',
library: 'AwesomeTable',
// libraryTarget: 'window'
},
module: {
rules: [
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
plugins: [
new ExtractTextPlugin('style.css')
//if you want to pass in options, you can do so:
//new ExtractTextPlugin({
// filename: 'style.css'
//})
]
};
First of all, you need to expose your lib, you can do that via defining library & libraryTarget: 'umd' properties.
Second, it is not recommended to publish lib as a bundle. Think about that scenario, You lib is composed from several parts, but not all of them are mandatory. When you ship your lib a a bundle, you are forcing your users to download redundant extra code.
The best practice today is to transpile your code via Babel to be compatible es5 and commonjs as a module system.
Recently, there is a trend to ship es6 modules in a separate folder, so that whenever your users will use bundles that supports tree-shaking, they will able to use it.

Webpack: Bundle.js - Uncaught ReferenceError: process is not defined

Here's my webpack.config.js
"use strict";
module.exports = {
entry: ['./main.js'],
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{test: /\.json$/, loader: "json"},
]
},
externals: {
React: 'react',
},
target: "node",
};
And Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jQuery from 'jquery';
import vis from 'vis';
import babel from 'babel-core';
The Bundle.js is inserted in my Index.html. The browser then gives the error:
Uncaught ReferenceError: process is not defined
at Object.measureMethods (bundle.js:1297)
at Object.<anonymous> (bundle.js:530)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:288)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:158)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:110)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:90)
What should I change in the webpack.config.js to make this error go away?
For Webpack 5, you can reference process/browser from the appropriate plugins part of webpack.config.js:
// webpack needs to be explicitly required
const webpack = require('webpack')
// import webpack from 'webpack' // (if you're using ESM)
module.exports = {
/* ... rest of the config here ... */
plugins: [
// fix "process is not defined" error:
new webpack.ProvidePlugin({
process: 'process/browser',
}),
]
}
Then run
npm install process
before building.
For namespaced environment variables (more secure) check lines 10 - 28 on this StackBlitz page.
With dotenv package:
Install dotenv:
yarn add -D dotenv or npm i -D dotenv
Add .env file in your project root with the required variables:
NODE_ENV=development
apiKey=w23io222929kdjfk
domain=example.domain.org
Define these variables with webpack.DefinePlugin:
// webpack.config.js
const webpack = require('webpack')
const dotenv = require('dotenv')
// this will update the process.env with environment variables in .env file
dotenv.config();
module.exports = {
//...
plugins: [
// ...
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
// ...
]
//...
}
Access environment variables in your source code:
// src/index.js
alert(process.env.NODE_ENV)
alert(process.env.apiKey)
StackBlitz example: https://stackblitz.com/edit/node-kdfi4z?file=index.js
You need to add a plugin to define your env (in webpack config):
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
This is how i resolved the
ReferenceError: process is not defined
error with Webpack 5
npm i --save-dev process
Delete the "node_modules" folder
Add const webpack = require('webpack'); at the top of your config file
In your webpack config file, plugin section, add below:
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
Also in the webpack add the alias like below:
resolve: {
alias: {
process: "process/browser"
},
Now do npm i
...and when you build your application the error will disappear.
you can read about webpck migration [here]
Webpack 5 removes the ability to access environment variables using the notation process.env.MY_ENV_VAR. I had this same problem because I was getting a Uncaught ReferenceError: process is not defined error in my browser console. From the documentation of porting from v4 to v5 of Webpack, they mention the following:
1. Before upgrading to v5, verify that you can easily do it
Try to set the following options in your webpack 4 configuration and
check if build still works correctly.
module.exports = {
// ...
node: {
Buffer: false,
process: false
}
};
webpack 5 removes these options from the configuration schema and will always use false.
You have to remove these options again when upgrading your
configuration for webpack 5.
2. Handling env vars because process was removed
Regarding Runtime Errors:
process is not defined.
webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code.
Want to support frontend and browser usage? Use the exports or imports package.json field to use different code depending on the
environment.
Also use the browser field to support older bundlers,.
Alternative: Wrap code blocks with the typeof process checks. Note that this will have a negative impact on the bundle size.
Want to use environment variables with process.env.VARIABLE? You need to use the DefinePlugin or EnvironmentPlugin to define these
variables in the configuration.
Consider using VARIABLE instead and make sure to check typeof VARIABLE !== 'undefined' too. process.env is Node.js specific
and should be avoided in frontend code.
Therefore, given the above information, it is possible to use environment variables using one of the two plugins below.
const webpack = require("webpack");
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
"process.env.MY_ENV_VAR": JSON.stringify(process.env.MY_ENV_VAR)
}),
new webpack.EnvironmentPlugin(['MY_ENV_VAR']); // <--This is shorthand, does the same thing as the DefinePlugin
],
};
Then in your production code it's still feasable to refer to the environment variable in the same way, example:
console.log(process.env.MY_ENV_VAR);
However, as they said in the documentation included above, using process.env is NOT the recommended way since that is Node.js specific.
Webpack 5, the easiest solution for me...
npm install dotenv-webpack --save-dev
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
To avoid error like denoted in the question I had have provide in webpack.config.js the next configuration (note defining variable level: process.env):
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env)
})
Now it works fine. I'm using webpack 5.30.0, Vue 2.6.12 and vuelidate 0.7.6.
Error I had before in browser console:
Uncaught ReferenceError: process is not defined
at Object.../node_modules/vuelidate/lib/withParams.js
It is not good thing, that browser client library "vuelidate" requires Node.js specific env variables. Confused build and runtime areas in library.
Works for me to allow reading env variables inside React, using "webpack": "^5.1.3",
webpack.config.js
const webpackConfig = {
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
],
};
:)
Having dotenv-webpack/dotenv in your webpack and still doesn't work on Angular? Most probably you're trying to access process.env when running the Angular app on the browser (without Angular Universal), e.g. by ng serve.
Run npm i -S process and then in polyfills.ts paste the code below
import * as process from "process";
window["process"] = process;
Alternatively, if that's not the case and you're looking for webpack to obtain environmental variables then (I don't know why no one suggested yet) dotenv-webpack is the simplest one.
const dotenv = require("dotenv-webpack");
const webpackConfig = {
plugins: [new dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Of course you need to have them defined in .env file at the root of your project.
If it is useful for someone:
I tried almost every approach in this thread unsuccessfully.
When I went deeper into the problem I realized that what was causing this error on my application was the usage of assert lib:
import * as assert from 'assert';
...
assert(myVariable !== undefined, "Try to update undefined myVariable ");
BTW: I'm using Angular#~11.2.7
My problem was process is undefined error on internet explorer 11 using webpack 5.
This is how I solved my problem with process.env.MY_ENV_VAR thanks to #ArianPopalyar.
Ref. Answer
In addition to her solution, I added EnvironmentPlugin in webpack.config.js:
...
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser'
}),
new webpack.EnvironmentPlugin({
PATH_MODERN: 'dist/modern/domready.min.js',
PATH_LEGACY: 'dist/legacy/domready.min.js',
DEBUG: false
}),
...
]
and using it in index.js
if (process.env.PATH_LEGACY) {
// ...
}
Easy way: prepend the variable "NODE_ENV" when you call webpack i.e. NODE_ENV=production webpack --watch

Pass an argument to Webpack from Node.js

I'm trying to build both minified and unminified versions of my app (js and css) using Webpack.
This can be easily done via command-line interface using -p or --optimize-minimize switch:
webpack
webpack -p
However, I would like to perform these actions with just one command, so I decided to write a small Node.js script which would run both of these Webpack builds:
var webpack = require('webpack');
var config = require('./webpack.config');
webpack(config, callback); // Build unminified version
So the question is: can I pass the aforementioned -p argument to Webpack from the Node.js script in order to build the minified version? Or maybe there is a simpler way of solving my particular problem?
Of course, I can use child_process.exec(), but I don't think it's an authentic Node.js way.
Create your default config to webpack an unminified version. Run webpack with that config. Change the configuration from code and run webpack again. Here is a code example.
var webpack = require('webpack');
//assuming the config looks like this.
var config = {
entry: "./entry.js",
output: {
devtoolLineToLine: true,
sourceMapFilename: "./bundle.js.map",
pathinfo: true,
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: []
};
webpack(config).run(); // Build unminified version
config.output.filename = 'bundle.min.js'
config.plugins = [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})];
webpack(config).run(); // Build minified version
Key p is an alias to setting node environment variable process.env.NODE_ENV="production" as described here

Categories

Resources