My JavaScript asynchronous function is executed twice with webpack - javascript

My javascript asynchronous function is executed twice but I can't figure out why.
I am using webpack and only one file is loaded on the page this is my articles.js
// articles.js
async function test() {
console.log('test');
}
test().then((items) => {
// code here
}
I have twice "test" in the console
// webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "development",
entry: {
app: "./src/index.js",
articles: "./src/js/pages/articles.js",
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Translates CSS into CommonJS
MiniCssExtractPlugin.loader,
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
};
Thanks for your help

Related

Using web-worker in the library, but the chunk file can not be found in react application

There are two separate repo:
Library repo
React Web application
library provide 2 functions
func1 without using web-worker
func2 using web-worker
// func2
export const func2 = () => {
//.....
const worker = new Worker(new URL('./web-worker/worker.ts', import.meta.url));
//.....
}
bundle files from webpack5
then import it in react web application
func1 works fine
but got this error when I calling the func2
below is webpack config for the library
const path = require('path');
const config = {
mode: 'production',
entry: './src/index.ts',
module: {
rules: [
{
test: /.ts$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: ['#babel/preset-env', '#babel/preset-typescript'],
},
},
],
},
output: {
filename: "index.js",
path: path.resolve(__dirname, 'dist'),
publicPath: "/",
library: {
type: 'umd',
},
},
resolve: {
extensions: ['.ts', '.js'],
},
devtool: 'source-map',
};
module.exports = config

Webpack bundle behaviour different from 5.21.0 and 5.22.0

I am doing some upgrades to node a package which uses webpack. The package used to use webpack 5.9 for generating a small bundle, then using eval() was extracting some js code.
This is the webpack conf:
function getBaseWebpackConfig() {
return {
context: path.resolve(__dirname, '../'),
mode: 'development',
entry: "./test/input/icon.js",
devtool: false,
output: {
path: outputDir,
filename: bundleFileName,
publicPath: '',
library: {
type: 'commonjs2',
}
},
module: {
rules: [
{
test: /\.svg/,
exclude: /node_modules/,
loader: svg-loader,
options: {}
}
]
}
}
}
Now, moving to 5.73.0, this behaviour has changed; tests stopped running. After doing some debug, I have found the following.
With webpack < 5.21.2 the bundle starts as:
module.exports =
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
With webpack > 5.22.0 the bundle starts as:
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
Essentially, it does not have a top module.exports anymore and this breaks the rest of the code.
I could not find any reason this. The changelog does not give me any clue. Might it be a bug?
I'm not a webpack expert. But, comparing yours with my webpack configs I created recently (using the latest webpack for a PWA app). My settings are inside a module.exports. Maybe that's why module.exports is not in your bundle. e.g.
module.exports = {
context: path.resolve(__dirname, '../'),
mode: 'development',
entry: "./test/input/icon.js",
devtool: false,
output: {
path: outputDir,
filename: bundleFileName,
publicPath: '',
library: {
type: 'commonjs2',
}
},
module: {
rules: [
{
test: /\.svg/,
exclude: /node_modules/,
loader: svg-loader,
options: {}
}
]
}
}
}
Plus I've got three webpack config files common,dev and prod and use merge to combine them.
e.g. my webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const path = require('path');
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
output: {
filename: "[name].bundle.js",
},
module: {
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
new ForkTsCheckerNotifierWebpackPlugin(),
]
});

WebPack output.library.type var is undefined

I am learning WebPack with a shortcode. In the code, we are trying to calculate the cube and square. They will suppose to store in a variable as per the following webpack.config.js.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const isDevelopment = process.env.NODE_ENV === 'development';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
library: {
type: 'var',
name: 'testVar'
},
filename: '[name].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
new HtmlWebpackPlugin({
hash: true,
title: 'Video Player Play Ground',
myPageHeader: 'Sample Video Player',
template: './src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.svg$/,
use: 'file-loader'
}
]
},
resolve: {
extensions: [
'.tsx',
'.ts',
'.js',
'.scss'
]
},
optimization: {
usedExports: true,
runtimeChunk: false,
minimize: false
}
};
module.exports = config;
As shown in the above config, we store the compiled javascript in the variable with the name "testVar".
The above approach working fine when we are using the following command line code "webpack --mode production"
In the final generated javascript file we have a line which equals to
testVar = webpack_exports;
Also, testVar.start is working fine.
But the above approach is not working when we are using the following command line "webpack serve --mode production" or "webpack serve"
When we run a local server, the testVar.start is undefined. I am not sure what I am doing wrong.
Following is the code we are using in the index.html file to call the start function, which we defined in our internal javascript
window.onload = function (){
alert(testVar);
console.log(testVar);
if(testVar.start !== undefined)
{
alert(testVar.start);
console.log(testVar.start);
testVar.start(3,2);
}
else {
alert("Start Function is undefined");
}
}
Also following is the code insight from index.ts and math.ts.
import {cube, square} from './math';
export function start(c:number, s:number) {
console.log(cube(c));
console.log(square(s));
}
export function square(x:number) {
return x * x;
}
export function cube(x:number) {
return x * x * x;
}
enter image description here
Finally, I got it working :-).
I need to add the following line in my webpack.config.js
devServer: {
injectClient: false
},
Following is the reference URL: https://github.com/webpack/webpack-dev-server/issues/2484
Don't forget to Vote it. Thanks.

module.exports error for webpack backend (node.js)

I'm trying to use webpack to bundle my backend code. It's currently using vanilla node.js where I'm using module.exports.x, and when I run webpack, it also outputs the export line i.e. module.exports.x. Now the problem is when I run nodemon on the file, it gives me the error TypeError: Cannot set property 'x' of undefined.
What's my resolution here?
my config file.
"use strict"
const path = require("path")
// const utils = require("./utils")
// const config = require("../config")
var fs = require("fs")
const NodemonPlugin = require("nodemon-webpack-plugin")
const nodeExternals = require("webpack-node-externals")
function resolve(dir)
{
return path.join(__dirname, "..", dir)
}
module.exports = {
context: path.resolve(__dirname, "../"),
entry: "./src/server/server.js",
output: {
path: path.resolve(__dirname, "../src/server"),
filename: "server-webpack.js",
},
plugins: [
new NodemonPlugin(),
],
resolve: {
extensions: [".js",".ts", ".tsx"],
alias: {
"#": resolve("src"),
"#": resolve("src/server")
}
},
devtool: "#inline-source-map",
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: [resolve("src"), resolve("test")]
},
{
test: /\.tsx?$/,
loader: "ts-loader",
},
]
},
externals: [
nodeExternals()
],
target: "node"
}

Waypoint npm - Error: Can't resolve 'waypoint

I have a vue project and installed waypoints
npm install waypoints
I try to import it
import waypoint from 'waypoints';
but get an error
Error: Can't resolve 'waypoints' in /Mypath
What am I doing wrong?
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
var WebpackNotifierPlugin = require('webpack-notifier');
var fs = require('file-system');
var CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
/*node: {
fs: "empty"
},*/
resolve: {
alias: {
'masonry': 'masonry-layout',
'isotope': 'isotope-layout'
}
},
entry: './main.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './public/assets'),
filename: 'bundle.[chunkhash].js',
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [{loader:'css-loader?sourceMap'}, {loader:'sass-loader', options: {
sourceMap: true,
}}],
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
]
},
plugins: [
new CleanWebpackPlugin(['assets/*', 'css/*'], {
root: '/Users/LEITH/sites/laravelleith/public',
verbose: true,
dry: false,
exclude: ['360lockturret.jpg'],
watch: true
}),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('app.[chunkhash].css'),
new WebpackNotifierPlugin(),
function() {
this.plugin('done', stats =>{
fs.writeFileSync(
path.join(__dirname, 'manifest.json'),
JSON.stringify(stats.toJson().assetsByChunkName)
)
});
}
]
};
Waypoints comes bundled in several flavours, even via NPM, but I couldn't work out if there's a default implementation or not. So that's why your typical import Waypoint from 'waypoints' directive doesn't work.
I resolved this for my "vanilla ES6 + Webpack" setup as follows:
import 'waypoints/lib/noframework.waypoints.min.js';
const waypoint = new Waypoint({
element: document.getElementById('myScrollTarget'),
handler: () => {}
});
Basically #markedup is right, waypoints comes with various flavours, after installing waypoints if you look into /waypoints/lib/ folder you will see zepto|jquery|noframework.waypoints.js .
In this case you would require to import it as full path i.e.
import 'waypoints/lib/noframework.waypoints.min.js';
or
window.waypoint = require('waypoints/lib/noframework.waypoints');

Categories

Resources