Webpack.config.js configuration - javascript

Hello i'm trying to install this repo https://github.com/aepsilon and i ran npm i --no-bin-links, npm i webpack -g and other package but i cannot find how to configure my webpack.config.js because i got this error everytime i run npm start
webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0
how can i configure my webpack.config.js https://github.com/webpack/webpack-dev-server/issues/183
here is my webpack.config.js and package.json
'use strict';
/* eslint-env node, es6 */
const path = require('path');
const webpack = require('webpack');
/////////////
// Utility //
/////////////
/**
* Recursively merges two webpack configs.
* Concatenates arrays, and throws an error for other conflicting values.
*/
function merge(x, y) {
if (x == null) { return y; }
if (y == null) { return x; }
if (x instanceof Array && y instanceof Array) {
return x.concat(y);
} else if (Object.getPrototypeOf(x) === Object.prototype &&
Object.getPrototypeOf(y) === Object.prototype) {
// for safety, only plain objects are merged
let result = {};
(new Set(Object.keys(x).concat(Object.keys(y)))).forEach(function (key) {
result[key] = merge(x[key], y[key]);
});
return result;
} else {
throw new Error(`cannot merge conflicting values:\n\t${x}\n\t${y}`);
}
}
/////////////////
// Base Config //
/////////////////
const srcRoot = './src/';
const commonConfig = {
entry: {
TMViz: [srcRoot + 'TMViz.js'],
main: srcRoot + 'main.js'
},
output: {
library: '[name]',
libraryTarget: 'var', // allow console interaction
path: path.join(__dirname, 'build'),
publicPath: '/build/',
filename: '[name].bundle.js'
},
externals: {
'ace-builds/src-min-noconflict': 'ace',
'bluebird': 'Promise',
'clipboard': 'Clipboard',
'd3': 'd3',
'jquery': 'jQuery',
'js-yaml': 'jsyaml',
'lodash': 'lodash',
'lodash/fp': '_'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
// Note on ordering:
// Each "commons chunk" takes modules shared with any previous chunks,
// including other commons. Later commons therefore contain the fewest dependencies.
// For clarity, reverse this to be consistent with browser include order.
// names: ['util', 'TuringMachine', 'TapeViz', 'StateViz'].reverse()
names: ['TMViz'].reverse()
})
],
module: {
loaders: [
// copy files verbatim
{ test: /\.css$/,
loader: 'file',
query: {
name: '[path][name].[ext]',
context: srcRoot
}
}
]
}
};
//////////////////////
// Dev/Prod Configs //
//////////////////////
const devConfig = {
output: {pathinfo: true}
};
const prodConfig = {
devtool: 'source-map', // for the curious
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}})
]
};
const isProduction = (process.env.NODE_ENV === 'production');
module.exports = merge(commonConfig, isProduction ? prodConfig : devConfig);
my package.json
{
"name": "turing-machine-viz",
"version": "1.0.0",
"description": "Turing machine visualization and simulator",
"homepage": "http://turingmachine.io",
"license": "BSD-3-Clause",
"author": "Andy Li <andy.srs.li#gmail.com>",
"repository": "aepsilon/turing-machine-viz",
"scripts": {
"clean": "trash build/ || rm -r build/",
"depgraph": "mkdir -p build/ && (cd src/ && madge . --dot) > build/depgraph.gv",
"depgraph-noext": "mkdir -p build/ && (cd src/ && madge . --dot -x \"`node -e \"console.log(Object.keys(require('../webpack.config').externals).map(s => '^'+s+'$').join('|'))\"`\") > build/depgraph-noext.gv",
"lint": "eslint --cache webpack.config.js src/",
"prod": "export NODE_ENV=production; npm run lint && webpack --progress --colors --display-error-details",
"start": "webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0",
"watch": "webpack --watch --progress --colors --display-error-details"
},
"dependencies": {
"webpack-dev-server": "^2.9.5"
},
"devDependencies": {
"eslint": "^3.0.0",
"file-loader": "^0.8.5",
"raw-loader": "^0.5.1",
"webpack": "^1.12.9"
}
}
https://imgur.com/a/qdP18

Change the webpack version to 1.15.0 and webpack-dev-server to 1.16.5.
In the webpack.config.js line 77 change loader: 'file', to loader: 'file-loader',
Run npm install
Then enjoy your Turing Machine.
Thanks

Related

ReactJs Production Code- Uncaught ReferenceError: process is not defined

So I have a bit of an issue with by ReactJs production code where it doesn't seem to recognize my environment variables. This is the error I get:
Uncaught ReferenceError: process is not defined
<anonymous> webpack://testProject/./src/agent.js?:9
js http://localhost:8080/src_Admin_MainPage_SessionTimeout_index_js-src_agent_js-node_modules_moment_locale_sync_recursive_.js:29
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
<anonymous> webpack://coralpanda/./src/Admin/MainPage/Login/index.js?:5
js http://localhost:8080/src_Admin_MainPage_index_js.js:28
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
<anonymous> webpack://coralpanda/./src/Admin/MainPage/index.js?:4
js http://localhost:8080/src_Admin_MainPage_index_js.js:128
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
I followed Webpack's documentation for passing in environment variables and added them to my package.json file's build settings, but it didn't work. Here's how it looks:
"scripts": {
"start": "react-scripts start",
"build": "webpack --mode=production --env REACT_APP_SERVER_URL=https://localhost:3481/project --env NODE_PATH=./src --node-env=production",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
},
And here is my webpack.config.js just in case:
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const isProduction = process.env.NODE_ENV == "production";
const stylesHandler = isProduction
? MiniCssExtractPlugin.loader
: "style-loader";
const config = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "build"),
},
devServer: {
open: true,
host: "localhost",
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: "babel-loader",
},
{
test: /\.s[ac]ss$/i,
use: [stylesHandler, "css-loader", "postcss-loader", "sass-loader"],
},
{
test: /\.css$/i,
use: [stylesHandler, "css-loader", "postcss-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: "asset",
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
resolve: {
alias: {
assets: path.resolve(__dirname, 'src/assets/'),
agent: path.resolve(__dirname, 'src/agent.js'),
"agent.js": path.resolve(__dirname, 'src/agent.js'),
Admin: path.resolve(__dirname, 'src/Admin'),
}
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
config.plugins.push(new MiniCssExtractPlugin());
config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
} else {
config.mode = "development";
}
return config;
};
Fixed the issue. The answer was EnvironmentPlugin. So I had to add that for webpack to recognize my environment variables. I added the following lines to my webpack.config.js:
const { EnvironmentPlugin } = require('webpack')
const config={
plugins:[
new EnvironmentPlugin({
REACT_APP_SERVER_URL: "https://localhost:3481/project",
NODE_PATH: "src/"
})
]
}

I need help adding environment variables to my TypeScript toolchain

I am requesting help setting up the compilation and dev environment for a typescript library. The library should work when consumed by a web app framework and when consumed by a script tag. I am currently using Webpack as a dev server so I can debug and TSC to build (cjs + esm). The issue that prompted this post was having to constantly switch my API strings between http://localhost:8080 to https://production.com. What tools or changes do I need in order to build dev and prod variables into my compilation?
Here is what I'm doing so far:
package.json fragment
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"files": [
"lib/**/*",
"README.md"
],
"scripts": {
"build:esm": "tsc -p tsconfig.json --outDir lib/esm --module ES2020 --sourceMap false",
"build:cjs": "tsc -p tsconfig.json --outdir lib/cjs --module commonjs --sourceMap false",
"clean:build": "rimraf lib",
"clean:serve": "rimraf dist",
"build": "rimraf lib && npm run build:esm && npm run build:cjs",
"serve": "rimraf dist && webpack-dev-server"
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const SRC = path.resolve(__dirname, 'src')
const ENTRTY = path.resolve(__dirname, 'src', 'debug.ts')
const DIST = path.resolve(__dirname, 'dist')
module.exports = {
mode: 'development',
context: SRC,
entry: ENTRTY,
output: {
path: DIST,
filename: 'index.js',
},
devtool: 'source-map',
devServer: {
contentBase: DIST,
writeToDisk: true,
host: '0.0.0.0',
port: 8080,
https: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
include: [SRC]
}
]
}
}
My toolchain does not currently allow me to do do this:
import Axios from 'axios'
import SocketIO from 'socket.io-client'
export const axios = Axios.create({
baseURL: process.env.SERVER_HTTP_URL, //<-- can't do env-vars with tsc build
withCredentials: true
})
typescript cant not do that, but gulp can do it
const replace = require('gulp-replace');
const { src, dest } = require('gulp');
exports.default = function() {
return src(['*.js'], {base: './'})
.pipe(replace('__XXXX__', 'some variables'))
.pipe(dest('./'));
}

Trying to create readable output bundle but error message:- Entry module not found: Error: Can't resolve './src/index.js'

I am using Webpack version 6.14.8 in an Asp.net Core Razor Pages application in Visual Studio 2019. I am trying to create a readable output file. Here is the structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
|-->dist (generated by webpack)
------->main.js (webpack bundle)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
The src/index.js file is blank index.js file.
The package.json: -
{
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"wbp": "webpack --entry ./src/index.js --output ./dist/main.js --mode development",
"build": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"lodash": "^4.17.20",
"startbootstrap-simple-sidebar": "^5.1.2",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0"
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
I am trying to create a readable output folder: -"dist/main.js" in wwwroot folder: dist/main.js. However, when I ran the command: npm run wbp, I received the following error message about the entry module could not be found: Error: Can't resolve './src/index.js' in C:\ directory folder: -
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >npm run wbp
>helloword#1.0.0 wbp C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
>webpack ./src/index.js --output ./dist/main.js --mode development
asset main.js 1.47 KiB [emitted] (name: main)
.dist/main.js 644 bytes built] code generated
ERROR in main
Module not found: Error: Can't resolve './src/index.js' in C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
webpack 5.1.3 compiled with 1 error in 858 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! HelloWorld#1.0.0 build: `webpack --config webpack.config.js --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the HelloWorld#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xxx\AppData\Roaming\npm-cache\_logs\2020-10-18T07_19_13_940Z-debug.log
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >
The dist/main file was created in the project directory and its contents are: -
/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is not neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
/******/ (() => { // webpackBootstrap
/*!**********************!*\
!*** ./dist/main.js ***!
\**********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
eval("/*\n * ATTENTION: The \"eval\" devtool has been used (maybe by default in mode: \"development\").\n * This devtool is not neither made for production nor for readable output files.\n * It uses \"eval()\" calls to create a separate source file in the browser devtools.\n * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)\n * or disable the default devtool with \"devtool: false\".\n * If you are looking for production-ready output files, see mode: \"production\" (https://webpack.js.org/configuration/mode/).\n */\n/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ })()\n;\n\n//# sourceURL=webpack://HelloWorld/./dist/main.js?");
/******/ })()
;
I looked at the url address:- https://webpack.js.org/configuration/devtool/, and I tried the "output.path" option: Output|webpack, but it did not work, when I ran the "npm run wbp" command.
How do I fix the issue of input: .src/index.js file is not found and how do I create a readable output: dist/main file?
Thank you in advance.
Current structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
----->dist (generated by webpack-created by the command: npm run build)
------->main.js (webpack bundle-created by the command: npm run build)
------->index.html (created by the command: npm run build)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
package.json
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "SET NODE_ENV='production' && webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.0",
"html-webpack-plugin": "^4.5.0",
"lodash": "^4.17.20",
"popper.js": "^1.16.1",
"startbootstrap-simple-sidebar": "^5.1.2",
"style-loader": "^2.0.0",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0",
"webpack-node-externals": "^2.5.2"
},
"dependencies": {
"#fullcalendar/core": "^5.3.1",
"#fullcalendar/daygrid": "^5.3.2",
"#fullcalendar/list": "^5.3.1",
"#fullcalendar/timegrid": "^5.3.1"
}
}
I updated the input and output files of the webpack.config.js file in development mode as follows: -
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'development',
entry: [
'babel-polyfill',
'./wwwroot/src/index.js'
],
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: 'main.js'
},
resolve: {
extensions: ['.js', '.json']
},
module: {
rules: [
{ test: /\.(js)$/, use: { loader: 'babel-loader', options: {presets: ['#babel/preset-react']} }},
{ test: /\.(sass|scsss|css)$/, use: ['style-loader', 'css-loader'] },
{ test: /\.(svg|eot|woff|woff2|ttf)$/, use: ['file-loader'] },
]
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], //in order to ignore all modules in node_modules folder
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin(),
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
}
and afterwards run the command:- npm run build

Jest in a Monorepo doesn't work if running from a specific package

I have monorepo and I'm trying to use jest to run tests. This is what I have
/
packages/
package1/
jest.config.js
jest.config.base.js
jest.config.js
any my config files are
// jest.config.base.js
module.exports = {
collectCoverage: true,
setupFiles: ['<rootDir>/jest.setup.js'],
preset: 'ts-jest',
testEnvironment: 'jsdom',
collectCoverageFrom: [
'<rootDir>/packages/**/*.ts'
],
testMatch: [
'<rootDir>/packages/**/__tests__/**/*.test.ts'
],
transform: {
'^.+\\.js?$': '<rootDir>/node_modules/babel-jest'
},
testPathIgnorePatterns: [
'/node_modules/',
],
coveragePathIgnorePatterns: [
'/node_modules/',
]
};
// jest.config.js (root dir)
const base = require('./jest.config.base');
module.exports = {
...base,
projects: [
'<rootDir>/packages/*/jest.config.js'
]
};
// jest.config.js (of a package)
const base = require('./../../jest.config.base');
module.exports = {
...base,
rootDir: '../..',
};
Running npm run test from root directory works, but if I run npm run test from one of the packages, I get
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import '#babel/polyfill';
^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (packages/package1/node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (packages/package1/node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
This seems to be related to how babel is configured in your project.
The way I did it is add a root babel config:
const presets = [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
];
module.exports = function babelConfig(api) {
api.cache(false);
return {
presets,
};
};
And then in each package extend this base config:
module.exports = function babelConfig(api) {
api.cache(false);
return {
extends: '../../babel.config.js',
};
};
In my root package.json I also have these:
"#babel/cli": "~7.8.4",
"#babel/core": "~7.8.4",
"#babel/preset-env": "~7.8.4",
"babel-jest": "~25.1.0",
"jest": "~25.1.0",
In my package package.json I have a prepare npm script that transpiles the ES6 to ES5:
{
...
"main": "lib/index.js",
"files": [
"lib"
],
"scripts": {
"prepare": "rm -rf lib && babel src --out-dir lib"
}
}

webpack 2: ERROR in ./public/bundle.js from UglifyJs Unexpected character '`'

I got 2 related issues:
First: when I run npm run build the bundle.js file is not minified but I do get a bundle.js.map file.
Second: when I run webpack -d I only get a minified bundle.js file (and no error) but when I run webpack -p then I get a bundle.js that is not minified, a bundle.js.map, and those errors:
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
My question(s):
shouldn't the behaviors of webpack -p and webpack -d be the
opposite?
why is bundle.js not minified when I run npm run build?
why do I get those Unexpected character errors when I use template strings in my modules?
package.json looks like that:
{
...,
"scripts": {
"build": "webpack --progress --watch"
},
"devDependencies": {
"babel-core": "^6.13.2",
"babel-loader": "^6.2.5",
"babel-preset-es2015-native-modules": "^6.9.4",
"eslint": "^3.3.1",
"eslint-config-airbnb": "^10.0.1",
"eslint-plugin-html": "^1.5.2",
"eslint-plugin-import": "^1.13.0",
"eslint-plugin-jsx-a11y": "^2.1.0",
"eslint-plugin-react": "^6.1.2",
"webpack": "^2.1.0-beta.21"
}
}
while webpack.config.js is like that:
const webpack = require('webpack'); // eslint-disable-line import/no-extraneous-dependencies
const nodeEnv = process.env.NODE_ENV || 'production';
module.exports = {
entry: {
filename: './app/app.js'
},
output: {
filename: './public/bundle.js'
},
modules: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015-native-modules']
}
}
]
},
devtool: 'source-map',
plugins: [
// uglify
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
output: { comments: false },
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
})
]
};
I did search both here and Google (and webpack docs…) but I can't find anything useful to me. Thanks!!
UglifyJS2 does not have ES6/Harmony support in its releases yet. However, there's the Harmony branch which allows you to minify/uglify files with ES6 syntax.
I can suggest you an alternative solution which could help you spend less build time to transpile all ES6 to ES5.
Simply specify UglifyJs in your package.json, and let npm handles the dependencies.
"uglify-js": "git://github.com/mishoo/UglifyJS2#harmony-v2.8.22",

Categories