Uncaught SyntaxError: expected expression, got '='

273 views Asked by At

I've recently ugrade my app from Node.js 14 to 18, Angular 12 to 16 and weback 3 to 5. I follow the migration guide for Webpack and Angular. When I run the app the Webpack compiled successfully but when I launch the home page of the app I don't even got the user interface and my console show me 2 Uncaught SyntaxError: expected expression, got '=' in the app.js and polyfills.js

here is my webpack.config.js

var path = require('path');
var webpack = require('webpack');


var optimization = {
  splitChunks: {
    chunks: 'async',
    minSize: 20000,
    minChunks: 1,
    maxAsyncRequests: 30,
    maxInitialRequests: 30,
    enforceSizeThreshold: 50000,
    cacheGroups: {
      defaultVendors: {
        test: /[\\/]node_modules[\\/]/,
        priority: -10,
        reuseExistingChunk: true,
      },
      default: {
        minChunks: 2,
        priority: -20,
        reuseExistingChunk: true,
      },
    },
  },
};
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

process.traceDeprecation = true

module.exports = env => {
  
  var config = {};
  config.node = { global: false };
  // optimization.splitChunks was used to avoid duplicated dependencies
  config.optimization = optimization;
  var NODE_ENV = env ? env.NODE_ENV || 'development' : 'development';
  var isTestWatch = NODE_ENV === 'test-watch';
  var isTest = NODE_ENV === 'test' || isTestWatch;
  var isProd = NODE_ENV !== 'development';
  console.info("Running Webpack with option env set to : " + NODE_ENV);

  
  if (isProd) {
    config.devtool = 'source-map';
  }
  else if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  if (!isTest) {
    config.entry = isTest ? {} : {
      'polyfills': './src/polyfills.ts',
      'vendor': './src/vendor.ts',
      'app': './src/main.ts' // our angular app
    };
  }

 
  config.output = isTest ? {} : {
    path: isProd ? root('../dist/client') : root('../dist/client'),
    publicPath: isProd ? '/' : '/', //http://localhost:8080
    filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
    chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
  };

  config.mode = NODE_ENV;

  config.resolve = {
    extensions: ['.ts', ".tsx", '.js', '.json', '.css', '.scss', '.html'],
    extensionAlias: {
      ".js": [".js", ".ts"],
      ".cjs": [".cjs", ".cts"],
      ".mjs": [".mjs", ".mts"]
    }
  };


  config.module = {
    rules: [
      
      {
        test: /\.(js|jsx|tsx|ts)$/,
        loader: 'babel-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[hash].[ext]'
            }
          }
        ]
      },


      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.css$/,
        include: root('src', 'app'),
        use: ['raw-loader', 'postcss-loader']
      },

      {
        test: /\.s[ac]ss$/i,
        use: [
          "style-loader",
          "css-loader",
          "sass-loader",
        ],
      },
      {
        test: /\.(scss|sass)$/,
        exclude: root('src', 'style'),
        use: ['raw-loader', 'postcss-loader', 'sass-loader']
      },

      {
        test: /\.html$/,
        use: [
          {
            loader: 'raw-loader',
          }
        ],
        exclude: root('src', 'public')
      }
    ]
  };

  config.plugins = [
    new webpack.DefinePlugin({

      'process.env': {
        ENV: JSON.stringify(NODE_ENV)
      }
    }),

    new webpack.LoaderOptionsPlugin({
      options: {

        tslint: {
          emitErrors: false,
          failOnHint: false
        },
        
        postcss: [
          autoprefixer({
            browsers: ['last 2 version']
          })
        ]
      }
    })
  ];

  if (!isTest && !isTestWatch) {
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html'
      })
    );
  }

  if (isProd) {
    config.plugins.push(
      new CopyWebpackPlugin([{
        from: root('src/public')
      }])
    );
  }

  config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' 
  };

  return config;
};

function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}

here is my package.json :

    {
  "name": "XXXX",
  "version": "XXXX",
  "license": "XXX",
  "author": "XXX",
  "scripts": {
    "watch": "webpack --watch --progress --color",
    "pack": "webpack --config webpack.config.js",
    "test": "jest"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "16.2.0",
    "@angular/cdk": "16.2.0",
    "@angular/common": "16.2.0",
    "@angular/compiler": "16.2.0",
    "@angular/core": "16.2.0",
    "@angular/forms": "16.2.0",
    "@angular/material": "16.2.0",
    "@angular/platform-browser": "16.2.0",
    "@angular/platform-browser-dynamic": "16.2.0",
    "@angular/platform-server": "16.2.0",
    "@angular/router": "16.2.0",
    "@circlon/angular-tree-component": "11.0.4",
    "bootstrap": "4.1.1",
    "codemirror": "5.38.0",
    "core-js": "3.32.1",
    "docexplore-common": "file:../common",
    "es6-promise": "4.2.4",
    "file-saver": "1.3.8",
    "font-awesome": "4.7.0",
    "grunt": "1.6.1",
    "lodash": "4.17.21",
    "moment": "2.29.4",
    "ngx-editor": "15.3.0",
    "ngx-moment": "^6.0.2",
    "ngx-pagination": "6.0.3",
    "rxjs": "7.8.1",
    "tslib": "2.4.0",
    "web-animations-js": "2.3.1",
    "zone.js": "0.13.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^16.2.0",
    "@angular-eslint/eslint-plugin": "14.0.0",
    "@angular/cli": "~16.2.0",
    "@angular/compiler-cli": "16.2.0",
    "@babel/cli": "^7.22.10",
    "@babel/core": "^7.22.10",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/plugin-proposal-decorators": "^7.22.10",
    "@babel/plugin-proposal-object-rest-spread": "^7.20.7",
    "@babel/preset-env": "^7.22.10",
    "@babel/preset-typescript": "^7.22.5",
    "@types/file-saver": "0.0.1",
    "@types/node": "17.0.34",
    "@typescript-eslint/eslint-plugin": "5.30.5",
    "@typescript-eslint/eslint-plugin-tslint": "5.30.5",
    "@typescript-eslint/parser": "5.30.5",
    "autoprefixer": "7.1.1",
    "babel-loader": "^9.1.3",
    "babel-plugin-parameter-decorator": "^1.0.16",
    "codelyzer": "6.0.2",
    "copy-webpack-plugin": "11.0.0",
    "css-loader": "6.8.1",
    "eslint": "8.19.0",
    "file-loader": "6.2.0",
    "html-loader": "4.2.0",
    "html-webpack-plugin": "5.5.3",
    "json-loader": "0.5.7",
    "mini-css-extract-plugin": "2.7.6",
    "null-loader": "4.0.1",
    "postcss-loader": "7.3.3",
    "raw-loader": "4.0.2",
    "rimraf": "2.7.1",
    "sass": "1.52.3",
    "sass-loader": "13.3.2",
    "shelljs": "0.8.5",
    "source-map-loader": "4.0.1",
    "style-loader": "3.3.3",
    "ts-loader": "9.4.4",
    "typedoc": "0.24.8",
    "typescript": "^5.1.3",
    "url-loader": "4.1.1",
    "webpack": "5.88.2",
    "webpack-cli": "5.1.4"
  }
}

And my babel.config.json :

{
"plugins": [
    [
        "@babel/plugin-proposal-decorators",
        {
            "legacy": true
        }
    ],
    "babel-plugin-parameter-decorator",
    "@babel/plugin-proposal-class-properties",
    "@babel/proposal-object-rest-spread"
],
"presets": [
    "@babel/preset-env",
    [
        "@babel/preset-typescript",
        {
            "onlyRemoveTypeImports": true
        }
    ]
],

}

here is my tsconfig.json :

    {
  "compilerOptions": {
    "outDir": "../dist/client",
    "target": "ES2022",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "lib": [
      "ES2022",
      "dom"
    ],
    "declaration": true,
    "emitDeclarationOnly": true,
    "isolatedModules": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "awesomeTypescriptLoaderOptions": {
    "forkChecker": true,
    "useWebpackText": true
  },
  "esModuleInterop": true
}

the webpack output : the webpack output :

The browser console error : The browser console error :

the line(s) of code that throws the error :

/***/ ((__unused_webpack_module, webpack_exports, webpack_require) => {

"use strict"; eval("webpack_require.r(webpack_exports);\n/* harmony export / webpack_require.d(webpack_exports, {\n/ harmony export / MyCollectionsComponent: () => (/ binding / MyCollectionsComponent)\n/ harmony export / });\n/ harmony import / var angular_core__WEBPACK_IMPORTED_MODULE_6_ = webpack_require(/! @angular/core / "./node_modules/@angular/core/fesm2022/core.mjs");\n/ harmony import / var docexplore_common__WEBPACK_IMPORTED_MODULE_0__ = webpack_require(/! docexplore-common / "../common/dist/index.js");\n/ harmony import / var services_context_service__WEBPACK_IMPORTED_MODULE_1_ = webpack_require(/! ../../services/context.service / "./src/app/services/context.service.ts");\n/ harmony import / var services_collection_service__WEBPACK_IMPORTED_MODULE_2_ = webpack_require(/! ../../services/collection.service / "./src/app/services/collection.service.ts");\n/ harmony import / var controls_grid_grid_module__WEBPACK_IMPORTED_MODULE_3_ = webpack_require(/! ../../controls/grid/grid.module / "./src/app/controls/grid/grid.module.ts");\n/ harmony import / var collectionsList_function__WEBPACK_IMPORTED_MODULE_4_ = webpack_require(/! ../collectionsList.function / "./src/app/collectionsList/collectionsList.function.ts");\n/ harmony import / var utils_snackbar_opensnackbar__WEBPACK_IMPORTED_MODULE_5_ = webpack_require(/! ../../utils/snackbar/opensnackbar / "./src/app/utils/snackbar/opensnackbar.ts");\nfunction _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }\nvar _dec, _dec2, _class, _class2, _descriptor;\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a Symbol.iterator method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it"return"; } finally { if (didErr) throw err; } } }; }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.proto = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.proto || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'transform-class-properties is enabled and runs after the decorators transform.'); }\n\n\n\n\n\n\n\n\n\n\nvar MyCollectionsComponent = (dec = (0,angular_core__WEBPACK_IMPORTED_MODULE_6.Component)({\n selector: "dex-mycollections",\n templateUrl: "./myCollections.component.html",\n styleUrls: ["./myCollections.component.scss"]\n}), dec2 = (0,angular_core__WEBPACK_IMPORTED_MODULE_6.ViewChild)(controls_grid_grid_module__WEBPACK_IMPORTED_MODULE_3.GridComponent, {\n "static": false\n}), _dec(_class = (_class2 = /#PURE*/function (_CollectionsListFunct) {\n _inherits(MyCollectionsComponent, _CollectionsListFunct);\n var _super = _createSuper(MyCollectionsComponent);\n /**\r\n * Créé une instance de MyCollectionsComponent\r\n * @param {ContextService} contextService service d'accès à l'utilisateur courant\r\n * @memberof MyCollectionsComponent\r\n */\n function MyCollectionsComponent(contextService, collectionsService, router, dialog, open, http) {\n var _this;\n _classCallCheck(this, MyCollectionsComponent);\n _this = _super.call(this, collectionsService, router, contextService, dialog, open, http);\n // Récupération de l'utilisateur courant pour avoir ses droits\n _this.contextService = contextService;\n _this.dialog = dialog;\n _initializerDefineProperty(_assertThisInitialized(_this), "dataGrid", _descriptor, _assertThisInitialized(_this));\n _defineProperty(assertThisInitialized(this), "user", docexplore_common__WEBPACK_IMPORTED_MODULE_0.User.AnymousUser());\n _defineProperty(_assertThisInitialized(_this), "myCollections", void 0);\n _defineProperty(assertThisInitialized(this), "tableDefinition", {\n "name": new controls_grid_grid_module__WEBPACK_IMPORTED_MODULE_3.ColumnDefinition(1, "Nom de la collection", function (collection) {\n return collection.name;\n }, true, true, true),\n "type": new controls_grid_grid_module__WEBPACK_IMPORTED_MODULE_3.ColumnDefinition(

/***/ }),

0

There are 0 answers