Webpack Node.js API and ES6 - javascript

I've created node API webpack compiler in ES6. Without es6 everything works well. But if I use es6, I get this:
[13:29:41] TypeError: Cannot read property 'concat' of undefined
at new NormalModuleFactory (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/NormalModuleFactory.js:115:51)
at Compiler.createNormalModuleFactory (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:586:31)
at Compiler.newCompilationParams (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:603:30)
at Compiler.compile (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:611:23)
at readRecords.err (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:284:11)
at Compiler.readRecords (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:479:11)
at hooks.run.callAsync.err (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:281:10)
at AsyncSeriesHook.eval [as callAsync] (eval at create (/private/var/www/MyProject/legacy/shop/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:6:1)
at AsyncSeriesHook.lazyCompileHook (/private/var/www/MyProject/legacy/shop/node_modules/tapable/lib/Hook.js:154:20)
at hooks.beforeRun.callAsync.err (/private/var/www/MyProject/legacy/shop/node_modules/webpack/lib/Compiler.js:278:19)
Process finished with exit code 1
This is my code:
import {Compiler} from 'webpack';
const config = require("./config/webpack.config");
class WebpackCompiler {
constructor(context) {
this.config = config;
this.compilerOptions = {};
this.compiler = new Compiler(context);
}
start() {
this.compiler.options = Object.assign({}, this.config, this.compilerOptions);
this.compiler.run().then((stats) => this._handleStats(stats)).catch((err) => this._handleErrors(err));
}
setOutput(output) {
this.compilerOptions.output = output;
}
setEntries(entires) {
this.compilerOptions.entry = entires;
}
_handleStats(stats) {
const statsErrors = stats.toJson();
if (stats.hasErrors()) {
console.error(statsErrors.errors.toString({
chunks: false,
colors: true
}));
}
if (stats.hasWarnings()) {
console.warn(statsErrors.warnings.toString({
chunks: false,
colors: true
}));
}
}
_handleErrors(err) {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
}
}
export const CompilerFactory = {
create: function (context) {
return new WebpackCompiler(context);
}
}
After this, something like this:
var compiler = CompilerFactory.create(WEBPACK_CONTEXT);
compiler.setEntries({bundle: "./js/main.js"});
compiler.setOutput("./js/compiled");
compiler.start();
And simple webpack config:
const path = require('path');
const sourcePath = path.resolve("MY_PATH_TO_ROOT");
const mode = process.env.NODE_ENV === 'production' || "development";
module.exports = {
mode: mode,
node: {
__dirname: true
},
watchOptions: {
poll: true
},
devtool: "eval",
entry: {},
output: {
filename: '[name].js'
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
sourceMaps: true
}
}
]
}
]
},
externals: {
"jquery": "jQuery"
},
resolve: {
modules: [
path.resolve(sourcePath, 'node_modules')
]
}
};
Problem is after calling method Run(). In NormalModuleFactory.js, problem is in this row:
this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules));
As I say, there is no much informations in the webpack documentation about using ES6. Do you everyone know, where is problem?
Thank you for your time.

Related

rails/webpacker module build fail issue from ./node_modules/mini-css-extract-plugin/dist/loader.js

I have upgraded #rails/webpacker from v4 to v5 (5.72.1, to be precise). While upgrading, I got following issue
ERROR in ./node_modules/croppie/croppie.css Module build failed (from
./node_modules/#rails/webpacker/node_modules/mini-css-extract-plugin/dist/loader.js):
TypeError: Cannot read property 'tap' of undefined
This is how I have setup my webpack config
const { environment } = require('#rails/webpacker');
const vue = require('./loaders/vue');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
const customConfig = {
resolve: {
fallback: {
dgram: false,
fs: false,
net: false,
tls: false,
child_process: false,
},
},
entry: {
vendor: ['babel-polyfill', 'vue', 'moment', 'axios'],
},
};
environment.splitChunks((config) => {
console.log('config', environment);
return {
...config,
...{
optimization: {
splitChunks: { chunks: 'all', name: '~' },
runtimeChunk: true,
},
},
};
});
environment.config.delete('node.dgram');
environment.config.delete('node.fs');
environment.config.delete('node.net');
environment.config.delete('node.tls');
environment.config.delete('node.child_process');
environment.config.merge(customConfig);
environment.plugins.append('VueLoaderPlugin', new VueLoaderPlugin());
environment.loaders.append('vue', {
test: /\.vue$/,
loader: 'vue-loader',
});
// Comment this if you need case-sensitive-paths-plugin in local development.
if (process.env.RAILS_ENV === 'development') {
environment.plugins.delete('CaseSensitivePaths');
// Only add en.js locale for local development.
environment.plugins.append('moment', new webpack.ContextReplacementPlugin(/moment[/\\]locale/, /(en).js/));
}
environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))));
environment.plugins.prepend(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
})
);
const config = environment.toWebpackConfig();
config.resolve.alias = {
jquery: 'jquery/src/jquery',
};
let sassLoader = environment.loaders.get('sass').use.find(item => item.loader === 'sass-loader')
sassLoader = {
...sassLoader,
options: {
...sassLoader.options,
sassOptions: {
...sassLoader.options.sassOptions,
includePaths: ["./node_modules"],
}
}
}
let miniCssExtractPlugin = environment.plugins.get('MiniCssExtract')
console.log('miniCssExtractPlugin', miniCssExtractPlugin)
environment.loaders.append('vue', vue);
environment.config.merge({
optimization: {
minimize: false,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i,
}),
],
},
resolve: {
alias: {
app: path.resolve(__dirname, '../../app/'),
},
},
});
module.exports = environment
This is the logs
If I comment import 'croppie/croppie.css' in the js file where it is used, the error goes away where croppie is a third party library.
Not sure if this issue is only while importing third party css file.

When I run vue-cli -service build -mode test.I get an error.Process is not defined. But using vue-cli -service build does not report this error

Uncaught ReferenceError: process is not defined
/storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/cordova.js?ver=md5:314:13 ReferenceError: process is not defined
at u (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:285918)
at s (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:285692)
at file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:739057
at l (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:739281)
at u (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:739729)
at c (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:739645)
at file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:740037
at file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/static/js/app.js:1:274361
at Object.callbackFromNative (file:///storage/emulated/0/Android/data/com.midea.out.css.test/files/www/com.midea.engineer.application.ms/cordova.js?ver=md5:293:58)
at <anonymous>:1:9
This is my vue.config.js configuration:
let webpack = require('webpack')
let CopyWebpackPlugin = require("copy-webpack-plugin");
let ZipPlugin = require("zip-webpack-plugin");
let path = require("path");
let buildConfig = require("./buildConfig");
let shell = require('shelljs');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const FileManagerPlugin = require('filemanager-webpack-plugin');
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
const IS_DEVELOPMENT = process.env.NODE_ENV === 'development';
console.log(process.env.NODE_ENV)
// 删除.zip包 并讲static里的资源copy至dist
var assetsPath = path.join(buildConfig.build.assetsRoot, buildConfig.build.assetsSubDirectory)
shell.rm('-rf', assetsPath)
shell.rm('-rf', '*.zip', path.resolve(__dirname, '../*.zip'));
shell.mkdir('-p', assetsPath)
shell.config.silent = true
shell.cp('-R', 'static/*', assetsPath)
shell.config.silent = false;
let exportConfig = {
assetsDir: 'static',
publicPath: './',
productionSourceMap: IS_PRODUCTION !== true,
configureWebpack: () => {
const plugins = [];
plugins.push(new HtmlWebpackPlugin({
filename: path.join(__dirname, './dist/index.html'),
template: 'index.html',
inject: true,
templateParameters(compilation, assets, options) {
return {
compilation: compilation,
webpack: compilation.getStats().toJson(),
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: options
},
process,
};
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'auto'
}));
if (process.env.NODE_ENV === "production") {
plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
// warnings: false,
drop_console: true,
pure_funcs: ["console.log"] //移除console
}
},
sourceMap: false,
parallel: true
})
);
// 按需加载
plugins.push(LodashModuleReplacementPlugin);
}
// 设置全局变量
let ENV_TYPE, CONF = path.resolve(__dirname, './src/projectConfig.js');
switch (process.env.NODE_ENV) {
case 'development':
ENV_TYPE = path.resolve(__dirname, './buildConfig/dev.env.js');
break;
case 'test':
ENV_TYPE = path.resolve(__dirname, './buildConfig/test.env.js');
break;
case 'production':
ENV_TYPE = path.resolve(__dirname, './buildConfig/prod.env.js');
break
}
plugins.push(new webpack.ProvidePlugin({
'$envType': ENV_TYPE,
'$conf': [CONF, 'default']
}));
if (!IS_DEVELOPMENT) {
let CopyWebpackPluginObj = [
{
from: path.join(__dirname, './CubeModule.json'),
to: path.join(__dirname, './dist/CubeModule.json'),
transform: function (content, path) {
if (!IS_PRODUCTION) {
// 对调版本号
const cubeModule = JSON.parse(content)
var temp = {
version: cubeModule.version,
build: cubeModule.build
}
for (var p in temp) {
cubeModule[p] = cubeModule['test' + p[0].toUpperCase() + p.slice(1)]
cubeModule['test' + p[0].toUpperCase() + p.slice(1)] = temp[p]
}
return new Buffer.from(JSON.stringify(cubeModule))
} else {
return new Buffer.from(content)
}
}
},
{
from: path.join(__dirname, './static'),
to: path.join(__dirname, './dist/static/'),
}
];
plugins.push(new CopyWebpackPlugin({patterns: CopyWebpackPluginObj}));
plugins.push(new FileManagerPlugin({
events: {
onEnd: {
archive: [
{
source: './dist',
destination: './' + IS_PRODUCTION === true ? buildConfig.build.zipName : buildConfig.buildTest.zipName
},
]
}
}
}));
// plugins.push(new ZipPlugin({
// path: path.join(__dirname, './'),
// filename: IS_PRODUCTION === true ? buildConfig.build.zipName : buildConfig.buildTest.zipName,
// }));
if (process.env.npm_config_report) {
// 打包后模块大小分析//npm run build --report
plugins.push(new BundleAnalyzerPlugin());
}
}
return {
plugins: plugins
}
},
chainWebpack: (webpackConfig) => {
// 删除预加载
// webpackConfig.plugins.delete('preload');
// webpackConfig.plugins.delete('prefetch');
// todo 按理说这个应该是不需要了
// webpackConfig
// .entry('./src/main.js')
// .add('babel-polyfill')
// .end();
/*设置资源夹路径*/
webpackConfig.resolve
.alias
.set("assets", path.join(__dirname, "src/assets"))
.set("$common", path.join(__dirname, "src/js/common.js"))
.set('#', path.join(__dirname, 'src'))
.set("#assets", "#/assets")
.set("#components", "#/components")
.set("#css", "#/assets/style")
.set("#img", "#/assets/images")
.set("#store", "#/store");
/*设置资源夹路径*/
webpackConfig.resolve
.extensions
.add('.js').add('.vue').add('.json');
// 压缩图片
webpackConfig.module
.rule("images")
.use("image-webpack-loader")
.loader("image-webpack-loader")
.options({
mozjpeg: {
progressive: true,
quality: 65
},
optipng: {
enabled: false
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false
}
})
.tap(options => Object.assign(options, { limit: 2040 }));
// 处理mp3
webpackConfig.module
.rule("mp3")
.test(/\.(mp3)$/)
.use("file-loader")
.loader("file-loader")
.end();
// webpackConfig.module
// .rule('js')
// .test(/\.js$/)
// .exclude
// .add('/node_modules/')
if (IS_PRODUCTION) {
// 代码压缩
webpackConfig.optimization.minimize(IS_PRODUCTION);
//分割代码
webpackConfig.optimization.splitChunks({
chunks: 'all'
})
}
webpackConfig.devtool(IS_PRODUCTION === true ? false : "source-map");
},
css: {
extract: IS_DEVELOPMENT !== true, // 是否使用css分离插件 ExtractTextPlugin 为true时不会热更新
sourceMap: false, // 开启 CSS source maps?
// 启用 CSS modules for all css / pre-processor files.
requireModuleExtension: false,
loaderOptions: {
css: {
// 这里的选项会传递给 css-loader
},
less: {
// data: `#import "~#css/variable.less";`
},
postcss: {
// 这里的选项会传递给 postcss-loader
}
}
},
// 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
parallel: require("os").cpus().length > 1,
devServer: {
port: 8080,
open: false
},
// 第三方插件配置
pluginOptions: {
'style-resources-loader': {
preProcessor: 'less',
patterns: [
// path.resolve(__dirname, 'src/assets/style/common.less'),
// path.resolve(__dirname, 'src/assets/style/mixins.less'),
// path.resolve(__dirname, 'src/assets/style/reset.less'),
// path.resolve(__dirname, 'src/assets/style/variable.less'),
]
}
}
}
module.exports = exportConfig
After running ue- CLi -service build -mode test, the packaged code contains process, which should be node environment, but cannot be run in the browser environment
The following screenshot code is where the error occurred. Because the project build typed in the Process, the error was reported when the browser was running. Does anyone know why this problem occurred
The reason is that there was a module that introduced import promise from 'promise', but this promise was not installed. The module then USES try catch so that ASAP types in the handling exception. However, ASAP, the processing module, UE - CLI - Server build - Mode test, does go into the Node environment.This representation is confusing, and you'll see that only if you configure Target :' Web ', you won't type process. However, the Target of Webpack is Web by default, so there should be some problems with #vue/ CLI.
The following problem detection is beyond my ability, so I have no intention to solve it. I hope someone can see more detailed explanation.

TypeError: Class constructor Document cannot be invoked without 'new'

I am working on a project(Next.js version 8.1.0) and I want to upgrade to version 9.2. I changed Next.js version to 9.2 and I am having this issue:
TypeError: Class constructor App cannot be invoked without 'new'
at new MyApp (/home/node/app/src/.next/server/static/development/pages/_app.js:4384:191)
at processChild (/home/node/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:2995:14)
at resolve (/home/node/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:2960:5)
at ReactDOMServerRenderer.render (/home/node/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3435:22)
at ReactDOMServerRenderer.read (/home/node/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
at renderToString (/home/node/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)
at render (/home/node/app/node_modules/next/dist/next-server/server/render.js:81:16)
at renderPage (/home/node/app/node_modules/next/dist/next-server/server/render.js:346:16)
at Object.ctx.renderPage (/home/node/app/src/.next/server/static/development/pages/_document.js:2266:26)
at Function.getInitialProps (/home/node/app/src/.next/server/static/development/pages/_document.js:1515:19)
at _callee$ (/home/node/app/src/.next/server/static/development/pages/_document.js:2282:77)
at tryCatch (/home/node/app/src/.next/server/static/development/pages/_document.js:428:40)
at Generator.invoke [as _invoke] (/home/node/app/src/.next/server/static/development/pages/_document.js:654:22)
at Generator.prototype.(anonymous function) [as next] (/home/node/app/src/.next/server/static/development/pages/_document.js:480:21)
at asyncGeneratorStep (/home/node/app/src/.next/server/static/development/pages/_document.js:124:24)
at _next (/home/node/app/src/.next/server/static/development/pages/_document.js:146:9)
Here is my next.config.js:
const withSass = require('#zeit/next-sass');
const { resolve } = require('path');
let baseUrl = process.env.BASE_URL;
baseUrl = baseUrl && baseUrl.length && '/' !== baseUrl ? baseUrl : '';
module.exports = withSass({
transpileModules: ['file-type'],
webpack(config, options) {
config.module.rules.push({
test: /\.tsx?$/,
use: [
{
loader: 'babel-loader',
options: {
configFile: resolve('babel.config.js'),
},
},
{
loader: 'ts-loader',
options: {
// disable type checker - we will use it in fork plugin
transpileOnly: true,
},
},
],
});
config.module.rules.push({
test: /node_modules\/file-type/,
use: [
{
loader: 'babel-loader',
options: {
configFile: resolve('babel.config.js'),
exclude: /node_modules\/(?!(file-type))/,
include: /node_modules\/file-type/,
sourceType: 'unambiguous',
},
},
],
});
config.resolve.extensions.push('.ts');
config.resolve.extensions.push('.tsx');
config.resolve.extensions.push('.jsx');
/* if (options.isServer) {
config.plugins.push(new ForkTsCheckerWebpackPlugin({ tsconfig: resolve('./tsconfig.json') }));
} */
return config;
},
pageExtensions: ['jsx', 'tsx'],
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: '[local]___[hash:base64:5]',
},
sassLoaderOptions: {
includePaths: [resolve('src/scss')],
},
webpackDevMiddleware: config => {
if (process.env.ENABLE_WATCH_POLL) {
const watchOptions = {
poll: true,
aggregateTimeout: 500,
ignored: [
'.git/**',
'src/.next/**',
'**/__tests__/**',
'.scannerwork/**',
'cypress/**',
'doc/**',
'node_modules/**',
'src/static/**',
],
};
return { ...config, watch: true, watchOptions };
}
return config;
},
publicRuntimeConfig: {
env: process.env.APP_ENV,
nodeEnv: process.env.NODE_ENV,
apiProxy: process.env.API_PROXY,
subscriptionKey: process.env.OCP_APIM_SUBSCRIPTION_KEY,
apiEndpoint: process.env.API_ENDPOINT,
serverPort: process.env.SERVER_PORT,
gmapApiendpoint: process.env.GMAP_API_KEY,
gigyaApiKey: process.env.GIGYA_API_KEY,
gigyaDatacenter: process.env.GIGYA_DATACENTER,
templateReimbursementLink: process.env.TEMPLATE_REIMBURSEMENT_LINK,
reimbursementStatusLink: process.env.REIMBURSEMENT_STATUS_LINK,
gtmId: process.env.GTM_ID,
captchaSiteKey: process.env.CAPTCHA_SITE_KEY,
baseUrl,
redisPort: process.env.REDIS_PORT,
redisHost: process.env.REDIS_HOST,
redisPassword: process.env.REDIS_PASSWORD,
},
});
From a comment in the GitHub issue you also have commented on it says to remove babel-loader from your next.config.js, as Next.js already includes this.

Webpack multi files with dependencies

I use Webpack to create a library to use in all of my projects (both client and server).
This is my webpack.config.js:
const path = require('path');
const libraryName = 'shared';
const config = {
mode: 'development',
entry: {
utils: `${__dirname}/src/shared/utils.js`,
enums: `${__dirname}/src/shared/enums.js`
},
devtool: 'inline-source-map',
output: {
path: `${__dirname}/dist`,
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true,
globalObject: 'typeof self !== "undefined" ? self : this'
},
externals: {
moment: {
commonjs: 'moment',
commonjs2: 'moment',
amd: 'moment',
root: 'moment'
}
},
module: {
rules: [{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/
}]
},
resolve: {
modules: [path.resolve('./node_modules'), path.resolve('./src')],
extensions: ['.json', '.js']
}
};
module.exports = config;
This is my enums.js:
import { EnvironmentMode} from './enums/config.enum';
export { EnvironmentMode };
This is my config.enum.js
const { enumUtils } = require('../utils/enum.utils');
// This enum defines the possible environment mode of the application.
const EnvironmentMode = enumUtils.createEnum(new Map([
['DEVELOPMENT', 'development'],
['TEST_LOCAL', 'test_local'],
['TEST_LOCAL_DEMO', 'test_local_demo'],
['TEST_DEMO', 'test_demo'],
['TEST_LINUX', 'test_linux'],
['PRODUCTION', 'production']
]));
module.exports = {
EnvironmentMode: EnvironmentMode
};
This is my utils.js:
import enumUtils from './utils/enum.utils';
export {
enumUtils
};
This is my enum.utils.js
class EnumUtils {
constructor() {}
// This method takes a map of elements and converts them to freeze objects (an enum-like object).
createEnum(mapItems) {
// Check the existence of the mapItems parameter. If not exists, return null instance.
if (!mapItems || mapItems.length <= 0) {
return null;
}
// This new object will hold the freeze array object.
const symbolMap = {};
// Assign each object.
mapItems.forEach((value, key) => {
symbolMap[key] = value;
});
// Freeze the object and return it.
return Object.freeze(symbolMap);
}
}
const enumUtils = new EnumUtils();
module.exports = enumUtils;
For some reason, when I build the project, and inject the compiled code to the projects, run any project, I get the following error:
C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:212
var EnvironmentMode = enumUtils.createEnum(new Map([['DEVELOPMENT', 'development'], ['TEST_LOCAL', 'test_local'], ['TEST_LOCAL_DEMO', 'test_local_demo'], ['TEST_DEMO', 'test_demo'], ['TEST_LINUX', 'test_linux'], ['PRODUCTION', 'production']])); // This enum define the possible error code types that can appear when the server is listening and running.
^
TypeError: Cannot read property 'createEnum' of undefined
at Object../src/shared/enums/config.enum.js (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:212:33)
at __webpack_require__ (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:30:30)
at Object../src/shared/enums.js (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:191:15)
at __webpack_require__ (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:30:30)
at ./src/shared/enums.js.Object.defineProperty.value (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:94:18)
at C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:97:10
at webpackUniversalModuleDefinition (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:3:20)
at Object.<anonymous> (C:\Or\Web\OSRStreamer\Streamer\streamer\src\shared\enums.js:10:3)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
What am I doing wrong?
My bad.
I did
const { enumUtils } = require('../utils/enum.utils');
Instead of
const enumUtils = require('../utils/enum.utils');
Fixed it. It works.

Issue with weakmap.get on IE11

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);
}
// ...
}

Categories