`document` is null after webpack vue.js - javascript

I try to build a project with vuejs and webpack.
this is my index.js
import Vue from 'vue'
import App from './app.vue'
console.log(document.body)
const root = document.createElement('div')
document.body.appendChild(root)
new Vue({
render:(h) => h(App)
}).$mount(root)
after webpack it to bundles.js, and run it on a browser, it rises:
as you can see,document beacames null.
why document does not works? this bug is my problems or from vue.js?
this is my webpack.config.js:
const path = require("path")
module.exports = {
entry:path.join(__dirname,"./src/index.js"),
output: {
path: path.join(__dirname,"dist"),
filename: "bundle.js"
},
module:{
rules:[
{
test: /\.vue$/,
loader:"vue-loader"
},
{
test:/\.css$/,
use:[
'style-loader',
"css-loader"
]
},
{
test:/\.(gif|jpg|jpeg|png|svg)$/,
use:[
{
loader: "url-loader",
options: {
"limit":1024,
name:"[name]-aaa.[ext]"
}
}
]
}
]
}
}
this is package.json
{
"description": "todolist",
"license": "MIT",
"scripts": {
"build": "webpack --config webpack.config.js"
},
"dependencies": {
"vue": "2.5.16"
},
"devDependencies": {
"webpack-cli": "^3.0.3",
"webpack": "^4.11.1",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"vue-loader": "^14.2.2",/*15. 版本不行*/
"vue-template-compiler": "^2.5.16"
}
}

I assume your index.js is placed in the head of your HTML and because the JavaScript resource is blocking, your body has not even been defined yet.
You need to either put the JavaScript after your elements that you are targeting, or you need to use the onload event.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

Related

webpack nodejs - Calling an external js file in script tag api call

I am new to nodejs, webpacks and javascripts, looking for assistance.
I have the below project structure using webpack with nodejs:
-dist
-node_modules
-public
--test.png
-routes
--web
---usage.html
--api
---testapi.js
-src
--app.js
-index.html
-package-lock.json
-package.json
-webpack.config.js
webpack.config.js has this structure:
webpack.config.js:
module.exports = {
mode: 'development',
target: "node",
entry: {
main: './src/app.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: [".js", ".jsx", ".json", ".css"]
},
module: {
rules: [
{
test: /\.(js|jsx)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/i,
loader: "html-loader",
},
//other rules
]
},
devServer: {
client: {
overlay: true
},
hot: true,
watchFiles: ['src/*', 'index.html'],
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
},
plugins: [
new CopyWebpackPlugin({
patterns: ['index.html']
}),
new HtmlWebpackPlugin({
filename: 'usage.html',
template: 'routes/web/usage.html',
}),
//other plugins
]
};
In testapi.js I have a api call using axios :
testapi.js:
const axios = require('axios');
var temp;
const config = {
//some_config
};
axios.get(some_url, config)
.then(async result => {
temp = result.data;
console.log("Results: " + JSON.stringify(temp))
})
.catch(error => {
console.log(error)
});
In usage.html I am calling the testapi.js script (also to cors issue as testapi.js is from a external api) and doing some actions as follows:
usage.html :
//other scripts
<script>
$(document).ready(function () {
$.getScript("testapi.js", async function (result) {
//some logic goes here
});
</script>
//body follows
package.json :
{
"name": //some_app_name,
"version": "1.0.0",
"description": //some_desc,
"dependencies": {
"#babel/core": "^7.18.13",
"async": "^3.2.4",
"aws-amplify": "latest",
"axios": "^0.27.2",
"express": "^4.18.1",
"html-webpack-plugin": "^5.5.0",
"node-fetch": "^2.6.7"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.2.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2016": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^6.4.1",
"extract-loader": "^5.1.0",
"file-loader": "^6.2.0",
"html-loader": "^4.1.0",
"html-webpack-partials-plugin": "^0.8.0",
"url-loader": "^4.1.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
},
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack",
"prestart": "npm run build",
"start": "webpack && webpack-dev-server --mode development"
}
}
I have tried the below things and nothing seems to be working:
Adding the js file as entry // The api gets called in console but with cors issue and not sure how i can use it in usage.html.
Added plugin in webpack config with :
new CopyWebpackPlugin({
patterns: ['routes/api/testapi.js']
}),
When I do this, I can see the raw code instead of the api response output in Network tab when I load that usage.html page.
Used $get instead of $getScript in usage.html.
Tried moving testapi to src as well and making necessary changes.
Kindly assist me with this

Hot Module Replacement Not working Reload always happening

I can't seem to figure out how to get hot module replacement to work. Every time I make a change to my html file or my CSS files the webpack always does a refresh to show the changes.
webpack.config.js
const path = require('path')
const postCSSPlugins = [
require('postcss-simple-vars'),
require('postcss-nested'),
require('autoprefixer'),
require('postcss-import')
]
module.exports = {
entry: './app/assets/scripts/App.js',
output: {
filename: 'bundled.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
watchFiles: ('./app/**/*.html'),
static: path.join(__dirname, 'app'),
hot: true,
port: 3000,
host: '0.0.0.0'
},
mode: 'development',
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader','css-loader', {loader: 'postcss-loader', options: {postcssOptions: {plugins: postCSSPlugins}}}]
}
]
}
}
package.json
"scripts": {
"dev": "webpack serve --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"autoprefixer": "^10.4.2",
"css-loader": "^6.6.0",
"postcss-import": "^14.0.2",
"postcss-loader": "^6.2.1",
"postcss-nested": "^5.0.6",
"postcss-simple-vars": "^6.0.3",
"style-loader": "^3.3.1",
"webpack": "^5.69.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
App.js
import '../styles/styles.css'
if(module.hot) {
module.hot.accept(function() {
console.log("Accepting the updated modules...")
})
}
What I've tried..
I've tried using the hotOnly option but its been removed
I've tried add an option tag in the CLI in my package.json file
Nothing seems to be working. Anytime I make a change the whole page refreshes.
To figure out how Hot Module Reload works and is set up you may take a look at my post here. Remove --host 0.0.0.0 if you don't use it with Docker.

Webpack 5 React component library UMD bundle with SourceMaps

I am attempting to make a webpack 5 build process to create a react component library I just had a couple of things cannot seem to get working.
#1) The webpack build command works fine, and when using the inline-source-map option I can
SEE the data URL embeded in the outputted build file but when I ever I attempt to publish and test this library on NPM I always get obfuscated errors without original lines of code so I can't even tell where the errors are; what else am I missing to activate source-maps? I am using Chrome dev tools and it doesn't even tell me a source map is available for that code...
#2) Another issue I am having is after building this with webpack into the dist folder; I start another CRA test app and try to pull components out of the built library but all I get are these errors.
./src/dist/index.js
Line 1:1: Expected an assignment or function call and instead saw an expression no-unused-expressions
Line 1:112: 'define' is not defined no-undef
Line 1:123: 'define' is not defined no-undef
Line 1:190: Unexpected use of 'self' no-restricted-globals
Line 1:466: Expected an assignment or function call and instead saw an expression no-unused-expressions
Line 1:631: Expected an assignment or function call and instead saw an expression no-unused-expressions
I am aware webpack 5 stopped bundling polyfills for Node but shouldn't this code run
if I place it in the src directory of a CRA application? This is bundled code shouldn't it work in the browser/ in another React application? I targeted UMD so I thought it would work in this environment
here is all the necessary info
Webpack.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: "./src/index.js",
devtool: "inline-source-map",
externals: [nodeExternals()],
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
library: {
name: "test",
type: "umd",
},
},
plugins: [new CleanWebpackPlugin()],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
include: path.resolve(__dirname, "./src"),
},
],
},
};
Package.json
{
"name": "test-lib",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "start-storybook",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"#storybook/addon-knobs": "^6.3.1",
"#storybook/react": "^6.3.10",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^4.0.0",
"node-sass": "^6.0.1",
"path": "^0.12.7",
"sass-loader": "^12.1.0",
"webpack": "^5.58.0",
"webpack-cli": "^4.9.0",
"webpack-node-externals": "^3.0.0"
}
}
Button.js (sample component)
import React from 'react'
import PropTypes from 'prop-types';
const Button = ({message = 'Hello world'}) => (
<button>{message}</button>
)
Button.propTypes = {
message: PropTypes.string.isRequired
}
export default Button
Build entry point (index.js)
export { default as Button } from "./components/Button";

Webpack creating separate JS files for few imports

I am trying to build a custom webpack configuration for a complex project. While building I have observed that webpack is generating separate JS file when I import babel-runtime/core-js/json/stringify. Can someone help me understand what's happening here and why webpack is generating a separate JS file.
package.json
{
"name": "react-boilerplate",
"version": "1.0.0",
"description": "A boilerplate for large scale react apps",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development",
"build": "sh -ac 'webpack --mode production ${DEPLOY_TARGET:+--env.target $DEPLOY_TARGET}'",
"build:production": "DEPLOY_TARGET='production' yarn build",
"build:staging": "DEPLOY_TARGET='staging' yarn build"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"#typescript-eslint/eslint-plugin": "2.x",
"#typescript-eslint/parser": "2.x",
"babel-eslint": "10.x",
"babel-loader": "^8.0.6",
"babel-preset-react-app": "^9.0.2",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"dotenv": "^8.2.0",
"eslint": "6.x",
"eslint-config-react-app": "^5.0.2",
"eslint-loader": "^3.0.2",
"eslint-plugin-flowtype": "3.x",
"eslint-plugin-import": "2.x",
"eslint-plugin-jsx-a11y": "6.x",
"eslint-plugin-react": "7.x",
"eslint-plugin-react-hooks": "1.x",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"react-hot-loader": "^4.12.15",
"stylelint": "^11.1.1",
"stylelint-config-standard": "^19.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-custom-processor-loader": "^0.6.0",
"stylelint-processor-styled-components": "^1.8.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2",
"webpack-merge": "^4.2.2",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"lodash": "^4.17.15",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
},
"peerDependencies": {
"stylelint": "^11.1.1"
}
}
webpack.config.js
const { DefinePlugin } = require('webpack');
const path = require('path');
// Webpack plugins
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWepackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { rootDir } = require('./utils');
const {
entryPath,
getEnvJson,
htmlTemplatePath,
outputDir,
publicDir,
sourceDir,
} = require('./utils');
module.exports = env => ({
// Configure's our app entry points
entry: {
main: entryPath,
},
// Configure's loaders to let webpact know how different extension should be
// loaded when bundling
module: {
rules: [
// Configure's babel loader for transpiling javascript, eslint loader
// for linting javascript, stylelint loader for css linting
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'stylelint-custom-processor-loader',
options: {
configPath: path.resolve(rootDir, '.stylelintrc.js'),
},
},
'eslint-loader',
]
},
// Configure's loaders for images
{
test: /.(png|jpg|jpeg|svg|gif)/,
use: 'file-loader'
},
]
},
// Configure's destination for the bundled code
output: {
path: outputDir,
},
// Configure's additions plugins to be used by webpack
// Order of plugins is important
plugins: [
// Removes all the contents of output folder(but not the folder itself)
// before every webpack build
new CleanWebpackPlugin(),
// Copies all contents of public folder as it is excluding index.html file
new CopyWepackPlugin([
{
from: publicDir,
to: outputDir,
ignore: ['index.html']
}
]),
// Injects target specific enviroment variables
new DefinePlugin({
'process.env': getEnvJson(env.target)
}),
// Uses `public/index.html` and creates a `index.html` file for the app
// by injecting the generated bundles javascript files
new HtmlWebpackPlugin({
template: htmlTemplatePath
}),
],
// Configure's custom behavior for how modules are resolved by webpack
resolve: {
modules: [sourceDir, 'node_modules']
}
});
.babelrc
{
"presets": ["react-app"]
}
That is because of your entryPath.
module.exports = {
entry: {
bundle1: '.src/fileForBundle1.js',
bundle2: '.src/fileForBundle2.js'
},
This would generate two bundles.
Make sure entryPath is not an object of multiple values.
Issue was with the file-loader regex which was incorrectly configured and which resulted in matching babel-runtime/core-js/json/stringify. So file-loader was being used to load it.

Can't resolve "app.js" - Webpack

Problem
So, i'm working a web app using Webpack and ES6. When I try to run Webpack, it tells me that it can't resolve "app.js". I've looked all across the internet for a solution, but I just couldn't find one, can someone help me?
The Full error is:
ERROR in ./assets/js/main.js
Module not found: Error: Can't resolve 'app.js' in 'C:\Users\sidna\Dropbox\Dev Stuff\Web Apps\Mondrian Generator\assets\js'
# ./assets/js/main.js 4:0-17
webpack.config.js
module.exports = {
entry: './assets/js/main.js',
output: {
filename: 'assets/js/build.js',
},
watch: true,
module: {
loaders: [
{
test: /\.scss$/, loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
],
}
};
app.js (Empty)
main.js
// SCRIPTS
require("app.js");
// STYLES
require("../css/large.scss");
package.json
{
"name": "mondrian-generator",
"version": "1.0.0",
"description": "Create your own Mondrian",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"css-loader": "^0.28.0",
"style-loader": "^0.16.1",
"webpack": "^2.4.1"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-preset-env": "^1.4.0",
"node-sass": "^4.5.2",
"sass-loader": "^6.0.3",
"script-loader": "^0.7.0",
"webpack": "^2.4.1"
}
}
When the import is neither an absolute path (starting with /) nor explicitly a relative path (starting with ./ or ../), it is resolved as a module, which means it's Loading from node_modules Folders.
Your app.js is not in node_modules, so you need to change it to a relative path (assuming it's in the same directory as main.js):
require("./app.js");
Webpack follows the import behaviour of Node.js, but it also allows you to change it with the resolve.modules option.

Categories

Resources