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

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

Related

How do I fix "require is not defined" error with Webpack and Babel?

I keep getting error Uncaught ReferenceError: require is not defined in browser even with Webpack and Babel. For some reason I never had to worry about this before. I'm not sure if this error is caused by updated packages or what. I set up a very simple test application for simplicity.
package.json
{
"name": "require-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "16.16.0"
},
"scripts": {
"build": "webpack --config webpack.config.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.18.10",
"#babel/preset-env": "^7.18.10",
"babel-loader": "^8.2.5",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
module.exports = {
target: "node",
mode: "production",
output: {
path: path.resolve(__dirname, 'dist'),
clean: true,
filename: (pathData) => {
return 'index.js'
},
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
}
src/index.js (js file before build)
const path = require('path');
console.log(path);
dist/index.js (js file after build)
(()=>{var r,e={17:r=>{"use strict";r.exports=require("path")}},t={};r=function r(o){var s=t[o];if(void 0!==s)return s.exports;var p=t[o]={exports:{}};return e[o](p,p.exports,r),p.exports}(17),console.log(r)})();
There're a few things on your code needing changed. First of all, you can't target to build for node while you run that code on browser which is wrong. Secondly, path is designed and built to run on node server specifically, however, there's a fallback for path on browser though which is called path-browserify. You can check its document to see how it works.
Anyway to sum up, you need to switch target as web in the end:
module.exports = {
target: "web",
// ...
}

Exposing variables from a library with webpack

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.

Preact SSR hot reload/rebuild

I am trying to add automatic browser refresh to the dev environment for my preact ssr build.
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start:client": "webpack -w",
"start:server": "babel-node server.js",
"dev": "yarn run start:client & yarn run start:server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.11.6",
"#babel/core": "^7.11.6",
"#babel/node": "^7.10.5",
"#babel/preset-env": "^7.11.5",
"babel-loader": "^8.1.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"express": "^4.17.1",
"preact": "^10.5.2",
"preact-render-to-string": "^5.1.10",
"preact-router": "^3.2.1"
}
webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, "dist"),
filename: "app.js"
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
mode: 'development'
};
server.js
const express = require('express');
const path = require('path');
const render = require('preact-render-to-string');
const { h } = require('preact');
const { App } = require('./src/App');
const app = express();
const HTMLShell = (html) => `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>preact ssr</title>
</head>
<body>
<div id="app">${html}</div>
<script src="./app.js"></script>
</body>
</html>
`;
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
const html = render(<App />);
res.send(HTMLShell(html));
});
app.listen(3001);
When I run yarn dev, the webpack is correctly watching for any changes and rebuilding. I have to manually refresh the browser to see the effects, is there a way to automate this?
It doesn't look like you have webpack-dev-server as part of this project, which is responsible for handling the live reloading of your browser as changes occur. Start by adding that to your project:
yarn add webpack-dev-server --dev
Then, replace the current scripts in your package.json with the following:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start:client": "webpack-dev-server",
"start:server": "babel-node server.js",
"dev": "yarn run start:client & yarn run start:server"
},
Running yarn dev should give you live reload with recompiling after making that change.

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)

Categories

Resources