Running into error when trying to run npm run dev command - javascript

I'm trying to follow a tutorial non javascript, so I'm trying to run webpack from node script but I've been getting this weird error, I've searched online but couldn't find the solution
the error:
C:\Users\Ahmad Usman\Desktop\9-forkify\webpack.config.js:2
const path = require("path");
^
below is the code (they are in different files though)
// INDEX.JS FIle
import num from "./test";
console.log(`num: ${num}`);
// TEST.JS FILE
console.log('imported module');
export default 23;
// PACKAGE.JSON
{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"dev": "webpack"
},
"author": "Ahmad Usman",
"license": "ISC",
"devDependencies": {
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
//WEBPACK.CONFIG.JS
const path = require("path");
const path = require("path");
module.exports = {
entry: "./src/js/index.js",
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js",
},
mode: "development",
};
and here is a screenshot of my command line interface
commandline screenshot1
and commandline screenshot2
Thanks

The error says :
SyntaxError: identifier 'path' has already been declared
So if you remove duplicate code it should work:
//WEBPACK.CONFIG.JS
const path = require("path");
const path = require("path"); <-- declared twice
module.exports = {
entry: "./src/js/index.js",
output: {

Related

NPM Node Dependency Issue - BigNumber is not defined

I am following the Set Protocol Getting Started tutorial. I am familiar with vanilla Javascript, but not with Node, NPM, Webpack etc. I picked up bare minimum info on these and have been trying to run the code described in the tutorial in a browser. You can find the latest code in this github repo.
index.html has following code:
<html>
<script src="main.js"></script>
<body>
<div>
Hello World!
</div>
</body>
</html>
package.json looks like this:
{
"dependencies": {
"#0xproject/typescript-typings": "^3.0.2",
"bignumber.js": "^5.0.0",
"setprotocol.js": "^1.2.9-rc1",
"web3": "^1.0.0-beta.36"
},
"name": "setprotocol",
"version": "1.0.0",
"description": "set protocol tutorial",
"author": "swapna",
"license": "MIT",
"private": true,
"devDependencies": {
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12"
}
}
webpack.config.js looks like this:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
node: {
fs: 'empty',
},
optimization: {
minimize: false
},
};
I see bignumber.js under node_modules in the root of my project:
I am building main.js by running npx webpack --config webpack.config.js
When I load index.html in the browser (running npm install http-server -g in the dist folder), I see following error in the browser's JS console:
main.js:203795 Uncaught (in promise) ReferenceError: BigNumber is not defined
at createStableSet (main.js:203795)
at Module.<anonymous> (main.js:203818)
at __webpack_require__ (main.js:20)
at main.js:84
at main.js:87
createStableSet # main.js:203795
(anonymous) # main.js:203818
__webpack_require__ # main.js:20
(anonymous) # main.js:84
(anonymous) # main.js:87
Code where the error happens:
What am I doing wrong? Please help!
In the module where you use BigNumber, you need to import it. Eg, if you have
// mymodule.js
(async () => {
const { units, naturalUnit } = await setProtocol.calculateSetUnitsAsnyc(
componentAddresses,
[new BigNumber(1), new BigNumber(1)],
// ...
Change it to
// mymodule.js
import BigNumber from 'bignumber';
(async () => {
const { units, naturalUnit } = await setProtocol.calculateSetUnitsAsnyc(
componentAddresses,
[new BigNumber(1), new BigNumber(1)],
// ...

How to import extension along with files in visual studio code?

Development using nodejs for running (--experimental-modules)
Current visual studio code intelligence import as below
import config from "./config";
but required as below
import config from "./config.js";
Without .js getting error as below
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module C:\Uday\Projects\practice-server\config imported from C:\Uday\Projects\practice-server\index.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:85:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
So i need visual studio code intelligence for importing with extension??
//index.js
import express from "express";
import config from "./config.js";
const api_app = express();
const api_port = config.api_port
api_app.listen(api_port, () => {
console.log(`Practice Server started on ${api_port}`);
});
//package.json
{
"name": "practice-server",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
//config.js
let config = function () { };
config.api_port = 6000;
export default config;
In the global settings (or the project settings), add the following configuration:
// Preferred path ending for auto imports.
// - auto: Use project settings to select a default.
// - minimal: Shorten `./component/index.js` to `./component`.
// - index: Shorten `./component/index.js` to `./component/index`
// - js: Do not shorten path endings; include the `.js` extension.
"javascript.preferences.importModuleSpecifierEnding": "js",
Note that at the moment this only works for auto imports (i.e via intellisense when referencing an export of another file and VSCode imports it automatically). It does not work with with autosuggest when typing the import statement manually.
I always used my config.js like this this. May be it can help you.
const config = require('./config');
//Now access value from config
const sys_dbconfig = config_data['sys_database'];
const user = configdata['system_admin_name'];
Here is my config.js
var config = {
"sys_database": {
"user": 'postgres',
"host": 'localhost',
"database": 'postgres',
"password": 'postgres',
"port": "5432"
},
"system_admin_name": "system",
"url":"http://xxx.xx.x.xxx:3000/wscalc1?wsdl"
}
module.exports = config;

npx webpack command cannot find module webpack.config.js

I'm following the official Webpack getting started guide and I get an error on the Using a Configuration section. It says to create a webpack.config.js file with:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
I then run the following command:
npx webpack --config webpack.config.js
The error I get is:
Cannot find module '/Users/Documents/Web_Development/tone/webpack.config.js'
The guide does not seem to give any ideas of what could be wrong here. Also my code editor is telling me there is an error with const path = require('path'); saying "Expected a JSON Object, array or literal;
My Directory structure:
webpack.config.json
package.json.lock
package.json
node_modules/
dist/
index.html
main.js
src/
index.js
package.json:
{
"name": "tone",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
The solution was to change the webpack.config.json file to webpack.config.js.
You have to make sure that the webpack.config.js file is in the root of your project.

Webpack Initialization Fails

I just got into Webpack following an online tutorial.
Whenever I run npm run dev the web pack doesn't run and gives me the error: Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.output has an unknown property 'fileName'. These properties are valid:
object { auxiliaryComment?, chunkFilename?, webassemblyModuleFilename?, globalObject?, crossOriginLoading?, jsonpScriptType?, chunkLoadTimeout?, devtoolFallbackModuleFilenameTemplate?, devtoolLineToLine?, devtoolModuleFilenameTemplate?, devtoolNamespace?, filename?, hashDigest?, hashDigestLength?, hashFunction?, hashSalt?, hotUpdateChunkFilename?, hotUpdateFunction?, hotUpdateMainFilename?, jsonpFunction?, chunkCallbackName?, library?, libraryTarget?, libraryExport?, path?, pathinfo?, publicPath?, sourceMapFilename?, sourcePrefix?, strictModuleExceptionHandling?, umdNamedDefine? }
-> Options affecting the output of the compilation.outputoptions tell webpack how to write the compiled files to disk.
Here are my files:
package.json
{
"name": "forkify",
"version": "1.0.0",
"description": "Forkify Project",
"main": "index.js",
"scripts": {
"dev": "webpack"
},
"author": "Sanjay",
"license": "ISC",
"devDependencies": {
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8"
},
"dependencies": {}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/js/index.js',
output: {
path: path.resolve(__dirname, 'dist/js'),
fileName: 'bundle.js'
},
mode: 'development'
}
your output object is wrong. ( fileName => filename )
const path = require('path');
module.exports = {
entry: './src/js/index.js',
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: 'bundle.js'
},
mode: 'development'
}

error: cannot find module html-webpack-plugin

I am in the process of working through a tutorial on Webpack, but after adding in HtmlWebpackPlugin and trying to run Webpack again, I get the following error:
Error: Cannot find module 'html-webpack-plugin'
    at Function.Module._resolveFilename (module.js:489:15)
...
I have tried installing the plugin both locally and globally and I get the error both times.
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: "./app.js", // bundle entry point
output: {
path: path.resolve(__dirname, 'dist'), // output directory
filename: "[name].js" // name of generated bundle
},
plugins : [
new HtmlWebpackPlugin({
template: "index.html",
inject: "body"
})
]
};
//package.json
{
"name": "hyperlocalnola",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^2.30.1"
}
}
//app.js
var msg = require("./contents.js");
document.write(msg);
//contents.js
module.exports = "hello friend!";
Sorry about the wall of text for what is probably something very simple, but I cannot find what is causing this anywhere. Thanks in advance.

Categories