Issue with weakmap.get on IE11 - javascript

I have a class using WeakMaps as follows
const myWeakMap = new WeakMap();
class myClass {
constructor(myObject) {
myWeakMap.set(this, myObject);
}
getProperty () {
return myWeakMap.get(this).property;
}
}
var instance = new myClass({property: 5});
console.log(instance.getProperty());
This works fine when using chrome, firefox, but on IE this throws a cannot read property 'property' of undefined error because myWeakMap.get(this) is undefined. Also when I use the production build property of Webpack that only does a uglify of the code the system works properly on IE. I am not sure what is different or what causes the issue and not sure how to debug the issue. Any help would be welcome.
Webpack configuration
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const BUILD_DIR_CLIENT = path.resolve(__dirname, "build-client");
const APP_DIR = path.resolve(__dirname, "src/client/main");
const SHARED_DIR = path.resolve(__dirname, "src/shared");
const extractCSS = new ExtractTextPlugin("main.css");
const extractLESS = new ExtractTextPlugin("[name].css");
const semanticCssPath = path.resolve(__dirname, "node_modules/semantic-ui-css/semantic.min.css");
const datePickerCssPath = path.resolve(__dirname, "node_modules/react-datepicker/dist/react-datepicker.css");
const elasticBuilderPath = path.resolve(__dirname, "node_modules/elastic-builder");
const ifdefOpts = {
build: process.env.BUILD_ENV,
"ifdef-verbose": true,
};
module.exports = {
entry: {
index: APP_DIR + "/client.jsx",
},
output: {
path: BUILD_DIR_CLIENT,
filename: "main_index.js",
},
module: {
rules: [
{
test: /\.less$/,
use: extractLESS.extract(["css-loader?importLoader=2&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader", "less-loader"]),
},
{
test: /\.css$/,
include: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader"]),
},
{
test: /\.css$/,
exclude: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader?importLoader=1&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader"]),
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: "url-loader?limit=100000",
},
{
test: /\.jsx?/,
include: [APP_DIR, SHARED_DIR, elasticBuilderPath],
use: ["babel-loader", "eslint-loader", {loader: "ifdef-loader", options: ifdefOpts}],
},
],
},
plugins: [
extractLESS,
extractCSS,
],
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
"#main": path.resolve(__dirname, "src/client/main"),
"#shared": path.resolve(__dirname, "src/shared"),
},
extensions: [".js", ".jsx", ".css", ".less"],
},
};

Writing an answer instead of a comment so I can post some code.
I could not reproduce the issue. The following code works the same on IE11 and Chrome for me.
var myWeakMap = new WeakMap();
function myClass(myObject) {
myWeakMap.set(this, myObject);
}
myClass.prototype.getProperty = function() {
return myWeakMap.get(this).property;
};
var instance = new myClass({property: 5});
console.log(instance.getProperty());
I suspect that the constructor of myClass somehow got undefined in your case. Can you please check it? To do so, insert a console.log in your constructor, and check the logs for output:
class myClass {
constructor(myObject) {
console.log("myClass.constructor", myObject);
myWeakMap.set(this, myObject);
}
// ...
}

Related

Doing a dynamic import in a loop, walking through the array, but I only get the first value

I am trying to do a dynamic import so that my classes are pulled by information from json. In json, I only have classes specified that I need to get inside the script. I make paths from strings to json then put them in an array.I make an import and put the values ​​into an array. But as a result, I only get the value of the first import, the rest is undefined. Tell me how to correctly perform dynamic imports inside a loop, or is there a fundamentally different approach altogether?
My index.js:
var popupsConfig = myConfig.popups
var popups = []
async function getPopups(popupsConfig) {
for (let i = 0; i < popupsConfig.length; i++) {
let obj = await
import (`../src/assets/popups/${myConfig.popups[i].popupType}`)
popups.push(obj.default)
}
}
getPopups(popupsConfig)
My webpack.config:
const webpack = require("webpack")
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
context: path.resolve(__dirname, '../src'),
mode: 'development',
devtool: "eval-source-map",
entry: {
entry: ['babel-polyfill', '../dev/index.js'],
},
devServer: {
port: 8080
},
experiments: {
topLevelAwait: true
},
resolve: {
alias: {
'#dev': path.resolve(__dirname, '../src/')
}
},
plugins: [
new HtmlWebpackPlugin({
template: '../dev/index.html'
}),
new CleanWebpackPlugin(),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
})
],
module: {
rules: [{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpeg|svg|gif)$/,
use: ['file-loader']
}, {
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
}
My .babelrc:
{
"plugins": ["dynamic-import-webpack", "#babel/plugin-syntax-dynamic-import"]
}
enter image description here

Uncaught ReferenceError: __webpack_require__ is not defined Deploying to server

I am getting this error when logging into our dev site. This is a part of our migration from .NET framework 4.5.2 to 4.7.2. Though I do not think that has much to do with it. If we publish straight from VS, the page loads fine. If it uses our pipeline, or we did not clear our dirs beforehand, we get this error (in the console browser).
ie-polyfill_aurelia-bootstrapper:1 Uncaught ReferenceError:
webpack_require is not defined
at eval (ie-polyfill_aurelia-bootstrapper:1)
at Object.0 (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at t (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
The process of our build should be exactly the same as building with NPM locally, and there are no errors given in the build process. Build is defined for both in the webpack.config.js as follows
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { ProvidePlugin, SourceMapDevToolPlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'XXXXXX';
const outDir = path.resolve(__dirname, 'Scripts', 'pub');
const srcDir = path.resolve(__dirname, 'App');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
var isDevBuild = true;
var dev;
if (process.env.NODE_ENV) {
dev = process.env.NODE_ENV.trim();
if (dev === "production") {
isDevBuild = true;
}
}
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
},
'sass-loader'
];
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
plugins: [
new TsConfigPathsPlugin(),
],
alias: {
// Enforce single aurelia-binding, to avoid v1/v2 duplication due to
// out-of-date dependencies on 3rd party aurelia plugins
'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding'),
'aurelia-bootstrapper': path.resolve(__dirname, 'node_modules/aurelia-bootstrapper')
}
},
entry: {
app: ['./ie-polyfill', 'aurelia-bootstrapper'],
vendor: ['jquery'],
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
// serve index.html for all 404 (required for push-state)
historyApiFallback: '/',
},
module: {
rules: [
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{
test: require.resolve("jquery"),
use: [
{
loader: "expose-loader",
options: "$"
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
// required polyfills for non-evergreen browsers
new ProvidePlugin({
Map: 'core-js/es6/map',
WeakMap: 'core-js/es6/weak-map',
Promise: 'core-js/es6/promise',
regeneratorRuntime: 'regenerator-runtime' // to support await/async syntax
}),
new AureliaPlugin({
aureliaApp: 'main'
}),
new ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new CheckerPlugin(),
new ExtractTextPlugin({
filename: production ? '[contenthash].css' : 'style-[id].css',
allChunks: true,
}),
].concat(isDevBuild ? [
new SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(outDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new UglifyJsPlugin()
]),
})
There do seem to be a few times a similar question has been asked, but there has not been a solution that worked. Thanks for any help provided.

How to limit scope of webpack

I'm currently trying to implement typescript into my backend, but since it's quite new to me, I'm trying to figure things out one by one in a test folder, however it seems like webpack is taking all of my files and trying to read them, which gives me errors like:
Duplicate identifier, Module '"xxxx"' has no default export, Cannot find name 'Proxy'., Cannot redeclare block-scoped variable 'xxxx'.
Here's my config file (still using webpack3 for reasons):
"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, "../src/server/test"),
entry: "./test.ts",
output: {
path: path.resolve(__dirname, "../src/server/test"),
filename: "bundle.js",
},
plugins: [
// new NodemonPlugin(),
],
resolve: {
extensions: [".js",".ts", ".tsx"],
alias: {
"#": resolve("src"),
"#": resolve("src/server")
}
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: [resolve("src"), resolve("test")]
},
{
test: /\.tsx?$/,
loader: "ts-loader",
},
]
},
externals: [
nodeExternals()
],
target: "node"
}

webpack - output.filename error

I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;

Webpack - Javascript/Es6

Just trying to run my app in Safari or Edge. http://ryanspice.com/test/
Unfortunately the console gives no errors, no compiling issues, and theres nothing signalling whats wrong. It seems to work perfectly in chrome and firefox.
Edit: From what I can tell the javascript is running
Here's my webpack.config.js
var path = require('path');
require("babel-core/register");
require("babel-polyfill");
var env = process.argv.indexOf('--env') === -1 ? false : true;
var spawn = require('child_process').spawn;
var source = {
input:{
js:'spice.js',
html:'./src/index.html',
path:'./src/',
},
output:{
js:"spice.js",
html:"../index.html"
}
}
var webpack = require('webpack');
var webpackPlugins = [];
if (env===true)
{
source.output.js = "spice.min.js";
var webpackUglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var webpackHtmlPlugin = require('html-webpack-plugin');
webpackPlugins.push(new webpackUglifyJsPlugin({ minimize: true }));
webpackPlugins.push(
new webpackHtmlPlugin({
filename: source.output.html, template:'./src/index.html'
})
);
}
module.exports = {
entry: ["babel-polyfill", source.input.path + source.input.js],
output: {
path: __dirname+"/bld/vendor",
filename: source.output.js
},
module: {
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")],
test: /\.jsx?$/
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
],
sassLoader: {
includePaths: [path.resolve(__dirname, "./css")]
}
},
plugins: webpackPlugins
};
Here's my .babelrc
{
"presets": ["es2015","stage-0"]
}

Categories