Exposing variables from a library with webpack - javascript

I don't seem to understand how webpack works. I would like to create a plain javascript library with some reusable components that I can use in other applications and in script tags in the html. So I tried to make a very simple library that exposes one variable containing a string. Should be simple I thought, but can't seem to get it to work.
My webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
library: {
name: 'mypack',
type: 'umd',
},
},
devtool: 'source-map',
devServer: {
watchContentBase: true,
contentBase: path.resolve(__dirname, 'dist'),
port: 9000
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader', 'css-loader']
}
]
},
}
My package.json:
{
"name": "mypack",
"version": "0.0.1",
"main": "./src/app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"start": "webpack ./src/app.js -d eval --watch --mode development",
"dev": "npx webpack serve"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.0.0",
"webpack": "^5.44.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"style-loader": "^3.2.1"
}
}
My src/app.js
let myvar = "test";
export {myvar};
My dist/index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"><title>test</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="main.js"></script>
</head>
<body>
Test
<script>
console.log(mypack.myvar);
</script>
</body>
</html>
mypack.myvar gives an 'undefined' in the console. mypack seem to be an empty object {}.
How can I access myvar in my package? What am I doing wrong?
Of course, this is only a dummy, in reality I would like to expose objects from the package.

In the end it seems to be a problem with the webppack-dev-server.
If I comment out the line 'contentBase: path.resolve(_dirname, 'dist'),' from the webpack.config.js, copy the index.html to the root of my package and change the script tag source to "dist/index_bundle.js" then it works.
Not sure what is going on there, the script seems to load just fine in the situation above (in the sourceview in the browser, I can click the link and I see the generated javascript) but doesn't seem to be working at all. But that's another question.

Related

Webpack Getting Started Project Not Running On Chrome, Fine on Firefox

I'm trying to run through the "Getting Started" section in Webpack's documentation here. I'm at the section before loading images - the .html file loads as expected ("Hello webpack" in red text) when I open it on Mozilla Firefox, but I get an Uncaught SyntaxError: Invalid or unexpected token (at bundle.js:2:8083) when I open it with Chrome. I'll include my index.js, dist/index.html, package.json, and webpack.config.js below:
index.js:
import _ from 'lodash';
import './style.css';
function component() {
const element = document.createElement('div');
// Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.classList.add('hello');
return element;
}
document.body.appendChild(component());
dist/index.html
<!doctype html>
<html>
<head>
<title>Asset Management</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
package.json
{
{
"name": "Webpack Demo",
"version": "0.0.0",
"license": "MIT",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js"
},
"dependencies": {
"lodash": "^4.17.21",
"three": "^0.140.0"
},
"devDependencies": {
"css-loader": "^6.7.1",
"style-loader": "^3.3.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
Please let me know if you can figure out what I'm doing wrong! Thanks

imported library function not defined from JavaScript webpack export

so I was following this https://webpack.js.org/guides/author-libraries/ from the web pack documentation, my file is just slightly different. No matter how I try to do this, I get various problems.
in my src/index.js file I have a simple function for example.
const Dinero = require('dinero.js')
export function calculateGrossRev(hudmonthly){
// Calculates the yearly gross rev
const hudonebr = Dinero({amount: hudmonthly, currency: 'USD'})
.multiply(12);
return hudonebr.getAmount();
}
In my package.json file I have.
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"dinero": "^1.0.1",
"lodash": "^4.17.21",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0"
},
"dependencies": {
"dinero.js": "^1.9.0"
}
}
In my webpack config file I have.
const path = require('path');
module.exports = {
mode: "development",
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'dinero-calc.js',
library: {
name: "dineroNumbers",
type: "umd",
},
},
};
when I run "npm run build", I get the big bundled file, all looks well to me.
I then have an index.html file I run with Live Server in VScode.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
</head>
<h1>TEST</h1>
<script src="./dinero-calc.js"></script>
<script>
console.log(window.dineroNumbers.calculateGrossRev(8200));
</script>
<body>
</body>
</html>
With the simple example from the docs I'm able to get the expected output from their expected function printed to the console, however with my imported function it says
index.html:11 Uncaught TypeError: Cannot read property 'calculateGrossRev' of undefined at index.html:11
I think a problem is in the script source url <script src="./dinero-calc.js"></script>. Please, check paths of index.html and dinero-calc.js.
According to your script tag, they should be in the same directory under dist folder.
[Upd]
First, install dinero.js which used in src/index.js.
npm i dinero.js
Also, dinero should be placed in dependencies, not devDependencies, because dinero.js used in your code.
Second, call function like this
Dinero.default({
amount: hudmonthly,
currency: "USD",
}).multiply(12);

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

Cannot find module "./foo.css" when using webpack as script

I'm need to use webpack as a script (not the typical config file) and be able to support css imports, however webpack/style-loader does't seem to be able to load a css import when it's outside the root directory.
directoryA/package.json
{
"name": "poc",
"version": "1.0.0",
"description": "",
"main": "poc.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"style-loader": "^0.28.8",
"style-loader": "^0.19.1",
"webpack": "^3.10.0"
}
}
directoryA/poc.js
const path = require("path");
const webpack = require("webpack");
let appPath = process.env.PWD;
webpack({
entry: path.join(appPath, 'app.js'),
context: appPath,
output: {
libraryTarget: 'umd',
path: path.join(appPath, 'out'),
filename: 'app.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
}
}).run(() => {
console.log("done");
});
directoryB/app.js
import './foo.css';
directoryB/foo.css
body { background-color: blue; }
directoryB/out/index.html
<html>
  <head><script src="app.js"></script></head>
<body></body>
</html>
steps to replicate:
cd directoryB/
node ../directoryA/poc.js
then open directoryB/out/index.html in the browser
result: "Error: Cannot find module "./foo.css"
expected: loading css style and getting a blue page
Note that, if out/index.html , app.js and foo.cs are inside directoryA instead, then running node poc.js actually yields the expected result, however outside, webpack or style-loader can't seem to find the file (note: also tried to use the modules: directive. both cases work if using importing a js file)

Access jQuery when loaded via webpack

I'm trying to get $ and jQuery to work in the DOM after loading them with webpack.
I will need jQuery for some extra dom manipulations that I will do with alongside video.js.
I've read through the webpack docs and this but although I can get jquery to work inside the bundle file with no problems, I can't seem to get it working outside of it.
My files in their current state:
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins : [
new webpack.ProvidePlugin({$: 'jquery',jQuery: 'jquery'})
],
};
index.html
<!DOCTYPE html>
<html>
<head>
<title>Webpack test</title>
</head>
<body>
<div id="playerContainer"> </div>
<script type="text/javascript" src="./dist/bundle.js"></script>
</body>
</html>
index.js
jQuery("body").css("background","red");
$("body").css("background","blue");
package.json
{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"jquery": "^3.2.1"
},
"devDependencies": {
"webpack-dev-server": "^2.4.5",
"webpack": "^2.6.1"
},
"scripts": {
"start": "webpack -w",
"server": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Is it possible to get jQuery (and maybe other libraries) to work in the browser?

Categories

Resources