Module functions after bundle with Webpack aren't recognized - javascript

I'm trying to bundle my node.js project into one single file, which would contain all the modules that it needs, by using webpack.
After creating a bundle.js file, I cannot run it because some functions from required modules are not recognized:
In the Server.js file I had required 'http' , and used http.createServer() function.
When I'm running the file, it says: TypeError: r.createServer is not a function
How can I bundle the project with all of it's modules correctly?
Relevant parts of my Package.json file:
"dependencies": {
"lodash": "4.17.4"
},
"devDependencies": {
"babel-loader": "^7.1.4",
"eslint": "^4.19.1",
"jasmine": "^3.1.0",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14"
},
"scripts": {
"test": "npm run lint && jasmine",
"lint": "sh util/lintRunner.sh",
"fix": "sh util/lintFixer.sh",
"build": "webpack -p",
"clean": "rm -rf dist/"
}
My webpack.comfig.js file:
const path = require('path');
module.exports = {
entry: [
'./Server/Server.js',
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
node: {
fs: 'empty',
dns: 'empty'
}
};

You need to tell WebPack where your bundled javascript is going to run; in this case in a nodejs environment.
Try adding target: 'node' to your configuration.
Read more about the target attribute: https://webpack.js.org/concepts/targets/

Related

Cannot resolve module in sibling directory

Good day all!
I am trying to setup a javascript workspace including the posibility to run test script using npm, webpack (and mocha for tests).
So my project structure looks someting like (npm generated files are omitted):
root
|- src
| |- main.js
| |- MyClass.js
|- test
| |- test.js
|- package.json
|- webpack.config.js
The main.js script is building and debugging fine. But the test script is giving me problems.
In short, I import classes from the project (from the src directory) for testing. But it cannot resolve it (eventhough intellisense of vscode is having no issues at all). So if my test-script looked something like:
import { MyClass } from 'MyClass'
/* testing stuff */
Intellisense is perfectly capable of resolving the location (as configured in the jsconfig.json), but eventhough I set the src directory as include-rule or as alias, webpack is not able to resolve it and tries to search in the /test directory instead (and in recursive order all its parent-directories, failing in the same manner).
So the question is how to let webpack resolve for 'nephew' directories?
(If there is an easier way to use mocha than with the current combined scripts, it would suffice in this case as well. So feedback on that is also welcome, but I defenitly would love to find the answer to the original question)
Here is the webpack.config.js content
const path = require('path');
{
name: "myProject_test",
mode: "development",
entry: path.resolve(__dirname, "./test/test.js"),
devtool: 'source-map' : '',
output:
{
clean: { dry: true },
path: path.resolve(__dirname, root, source.outputDir),
filename: "[id]/[name].js",
},
module:
{
rules:
[
{
test: /.jsx?$/,
include: [path.resolve(__dirname, "./test"), path.resolve(__dirname, "./src")],
exclude: [path.resolve(__dirname, "./dist"), path.resolve(__dirname, "./test/test-dist"), path.resolve(__dirname, "./node_modules")],
loader: 'loader-type',
options: { /* All loader types follow this pattern; so the rest is omited for brevety, but basically this includes all the loaders required for correct compiling */ }
}
],
},
resolve:
{
alias:
{
"*": [path.resolve(__dirname, "./src/*"), path.resolve(__dirname, "./test/*")],
},
extensions: ['.json', '.js', '.jsx', '.scss', '.sass', '.html', '.htm']
},
devServer:
{
contentBase: [path.resolve(__dirname, "./test"), path.resolve(__dirname, "./test/test-dist")],
/* Other server properties to make this work with server utility */
}
}
And here the package.json file content
{
"name": "MyProject",
"version": "0.0.1",
"description": "some description",
"dependencies": {},
"scripts": {
"test": "webpack && mocha test/test-dist --require source-map-support/register --reporter spec --check-leaks --recursive && rm -rf test/test-dist",
"debug": "webpack serve",
"start": "webpack --watch",
"build": "webpack"
},
"devDependencies": {
"#babel/core": ">=7.x",
"#babel/preset-env": ">=7.x",
"babel-loader": ">=8.x",
"cross-env": ">=7.x",
"css-loader": ">=6.x",
"html-loader": ">=2.x",
"resolve-url-loader": ">=4.x",
"style-loader": ">=3.x",
"sass-loader": ">=12.x",
"sass": ">=1.x",
"mini-css-extract-plugin": ">=2.x",
"extract-loader": ">=5.x",
"webpack": ">=5.x",
"webpack-cli": ">=4.x",
"webpack-dev-server": ">=3.x",
"worker-loader": ">=3.x",
"source-map-support": ">=0.x",
"mocha": ">=8.x",
"should": ">=13.x"
}
}

Webpack not building the most recent changes

I am working on a fairly simple project from https://medium.com/ethereum-developers/the-ultimate-end-to-end-tutorial-to-create-and-deploy-a-fully-descentralized-dapp-in-ethereum-18f0cf6d7e0e
Since the tutorial doesn't focus on the frontend part(webpack and babel and other things), I picked up these steps from different places.
Now I was trying to build the front using webpack and http-server, but I realized that it is not updating with the changes that I am making to the file.
webpack.config.js
const path = require('path')
module.exports = {
entry: path.join(__dirname, 'src/js', 'index.js'), // Our frontend will be inside the src folder
output: {
path: path.join(__dirname, 'dist'),
filename: 'build.js' // The final file will be created in dist/build.js
},
module: {
rules: [{
test: /\.css$/, // To load the css in react
use: ['style-loader', 'css-loader'],
include: /src/
}, {
test: /\.jsx?$/, // To load the js and jsx files
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}]
}
}
package.json
{
"name": "test-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"css-loader": "^3.5.3",
"json-loader": "^0.5.7",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"style-loader": "^1.2.1",
"web3": "^0.20.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"directories": {
"test": "test"
},
"dependencies": {},
"description": ""
}
I build it using
npx webpack --config webpack.config.js
and then serve it
http-server dist/
How do I fix this? And is this even the right way to do it?
Thanks.
U have already webpack-cli installed in your dependencies so u dont have to add config in command:
First Add Webpack Script in your Package.json:
"scripts": {
"watch": "webpack --watch",
},
When u run npm run watch --watch webpack will continue to watch for changes in any of the resolved files.
And for Server I recommend you webpack-dev-server
npm i webpack-dev-server
can be used to quickly develop an application
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
And add it to your npm script
"scripts": {
"watch": "webpack --watch",
"start": "webpack-dev-server --hot --open",
}
Now we can run npm start from the command line and we will see our browser automatically loading up our page. If you now change any of the source files and save them, the web server will automatically reload after the code has been compiled.
Advise: you must add html file in dist or plugins for webpack HtmlWebpackPlugin

webpack bundles files but index.js isn't running

I have an index.js file that imports my CSS and a few packages, but after bundling everything and starting the server I noticed that index.js wasn't running. I did a simple console.log in index.js and it isn't reached.
I copied the contents of my webpack.config file from a previous project which was working correctly, so I'm not sure if it's a file structure/path error or what not. Any thoughts?
Directory structure:
webpack.config.js:
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
var $ = require("jquery");
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
module.exports = {
entry: "./src/index.js", // removing the . fails the build
output: {
filename: './SiteAssets/scripts/RecruitmentTracking.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader']
}, {
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
],
},
devServer: {
disableHostCheck: true
},
devtool: 'cheap-module-eval-source-map', // this helps the browser point to the exact file in the console, helps in debug
devServer: {
contentBase: path.join(__dirname, 'src'),
historyApiFallback: true // this prevents the default browser full page refresh on form submission and link change
},
plugins: [
HtmlWebpackPluginConfig,
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
})]
}
index.js:
import "./RecruitmentTracking.css";
import 'jquery';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import 'jquery-ui-bundle/jquery-ui.min.js';
console.log('this is index.js');
package.json:
{
"name": "recruitmenttracking",
"version": "1.0.0",
"description": "Recruitment Initiatives Tracking",
"main": "index.js", // ----- should a more specific file path be here?
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open --mode development",
"build": "webpack --config webpack.config.js",
"dev-server": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#babel/polyfill": "^7.4.0",
"axios": "^0.18.0",
"bootstrap": "^4.3.1",
"jquery": "^3.3.1",
"jquery-ui-bundle": "^1.12.1-migrate",
"pdfmake": "^0.1.54",
"popper": "^1.0.1"
}
}
What's happening here is:
1 - webpack compiles and outputs into: './SiteAssets/scripts/RecruitmentTracking.js'
2 - HtmlWebpackPlugin, will then read the template file './src/index.html', and inject RecruitmentTracking.js script inside the body.
3 - then, it outputs the result to dist/RecruitmentTracking.txt
I don't see any problem, apart from the file being a .txt and not .html. and would obviously not be interpreted by the browser.
Try outputting to an html file instead, it should work
1) For some reason you've configured the following plugin to output a .txt file. So don't expect the browser to intepret that as a html file
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
2) Also I believe that file that you're opening in the browser is /dist/index.html and that file doesn't load your js file. Try adding the following line into /dist/index.html:
<script src"./SiteAssets/scripts/RecruitmentTracking.js"></script>
3) If the above works, please still consider taking a closer look at (1)
You have named the output file in HtmlWebpackPluginConfig as RecruitmentTracking.txt. change it to index.html and it should work
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html', // webpack takes ./src/index.html as input file
filename: 'index.html', // webpack processes the above input template and should output to index.html
inject: 'body'
});

react, wepack, babel, node, npm start error

ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '#babel/preset-es2015' from 'F:\reactapp'
at Function.module.exports [as sync] (F:\reactapp\node_modules\resolve\lib\sync.js:43:15)
at resolveStandardizedName (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:101:31)
at resolvePreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:58:10)
at loadPreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:77:20)
at createDescriptor (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:154:9)
at items.map (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:50)
at Array.map ()
at createDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:29)
at createPresetDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:101:10)
at passPerPreset (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:58:96)
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./main.js main[2]
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 448 bytes {0} [built]
[./node_modules/lodash/lodash.js] 527 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
i ?wdm?: Failed to compile.
Terminate batch job (Y/N)?
package.json file:
package json file is as follows. I followed https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"name": "reactapp",
"version": "1.0.0",
"description": "demo project",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [
"[]"
],
"author": "manjunathan g",
"license": "ISC",
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/preset-react": "^7.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.2.3",
"#babel/preset-env": "^7.2.3",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0"
}
}
babel config:
Babel config file is as below; followed as per https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"presets":["env", "react"]
}
webpack config
webpack config is as follows:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/react', '#babel/es2015'],
plugins: ['#babel/proposal-class-properties']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The #babel/preset-es2015 package has been deprecated and you can no longer install it from NPM.
The recommendation now is to use #babel/preset-env instead.
There are a lot of mistakes in your file configuration. Let me try to solve it:
.babelrc
You don't need the following devDependencies: babel-core, babel-preset-env, babel-preset-react and babel-preset-es2015. They are deprecated since Babel 7 was realeased. Substitute your code to this:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
webpack.config.js
Since webpack 4 was released, you don't need to inform the entry and output fields (You can do it for custom configurations). By default, webpack will look for index.js file located in the src/ directory (this directory must be in the root of your project). Webpack will create the module dependency graph from this file and output the bundled file to the dist/ directory. Try to configure your webpack.config.js like this:
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
module: {
rules: [
{
test: /\.jsx$/,
exclude: /node_modules/,
use: { loader: "babel-loader" }
},
{
test: /\.html$/,
use: { loader: "html-loader" } //Install it: 'npm i -D html-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html" // Put the index.html in the src/ directory
})
]
}
I'm not an expert in configuring webpack and I don't know if I could help you. I wrote an article on medium setting the environment to work with react, babel and webpack, but it is in portuguese. If you want to check: https://medium.com/#brunonakayabu/react-webpack-e-babel-configurando-o-ambiente-de-desenvolvimento-c7ee8a994222

Webpack css-loader: "Module not found: Error: Can't resolve 'main.css' in ..."

I am trying to include my css in the server hosted by webpack-dev-server. For that to happen, I apparently have to use style-loader and css-loader together, in order to bundle the css into the JavaScript.
I can't get it to work.
I follow the instructions here, yet I get the following error:
ERROR in ./src/index2.js
Module not found: Error: Can't resolve 'main.css' in C:\Users\magnusga\Downloads\Programming\TestPrograms\test\src'
# ./src/index2.js 1:0-27
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index2.js
I know for certain that main.css is in the same folder as index2.js
My Settings
index2.js
import css from 'main.css';
// ...much more code
webpack.config.js
module.exports = {
entry: {
app: './src/index2.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader']
}
],
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Development',
template: 'src/index.html',
inject: 'head'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index2.js",
"dependencies": {
"rxjs": "^5.5.6"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"postcss-loader": "^2.1.3",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"buildb": "babel src --watch --out-dir built --copy-files",
"watch": "webpack --watch",
"start": "webpack-dev-server",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
One Fix
One fix is to use import css from './main.css'; instead of import css from 'main.css'; (note the ./ infront of the file name).
That does not feel right though, because the css-loader site shows that it should be the latter, not the former.
Is it a typo in the docs?
Thank you.
It is not really a typo. If you import it like this:
import css from 'main.css';
Webpack thinks, that you want to import a module, and searches for this file under node_modules. This is necessary, when you for example installed the bootstrap package and want to import its css. So when your css file comes from a dependency, you import that dependency like this. But when you want to import a lokal file, always use relative paths.
So it must be: import css from './main.css';
Further Reading:
https://webpack.js.org/concepts/module-resolution/#module-paths
https://webpack.js.org/configuration/resolve/#resolve-modules

Categories

Resources