PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR ReferenceError: Can't find variable: Map - angularjs

I have used "MVC ASP.NET Core with Angular" template.
I am trying to include phantomJS and run the tests, but i get the following errors:
ERROR in [at-loader] ..\\node_modules\zone.js\dist\zone.js.d.ts:122:11 TS2451: Cannot redeclare block-scoped variable 'Zone'.
ERROR in [at-loader] ..\\node_modules\zone.js\ dist\zone.js.d.ts:363:14 TS2300: Duplicate identifier 'HasTaskState'.
ERROR in [at-loader] ..\\node_modules\zone.js\ dist\zone.js.d.ts:372:14 TS2300: Duplicate identifier 'TaskType'.
ERROR in [at-loader] ..\\node_modules\zone.js\ dist\zone.js.d.ts:458:15 TS2451: Cannot redeclare block-scoped variable 'Zone'.
PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR ReferenceError: Can't find variable: Map at ../wwwroot/dist/vendor.js:12460
Below are the node module version i have been using(package.json):
"dependencies": {
"#angular/animations": "4.1.2",
"#angular/common": "4.1.2",
"#angular/compiler": "4.1.2",
"#angular/core": "4.1.2",
"#angular/forms": "4.1.2",
"#angular/http": "4.1.2",
"#angular/platform-browser": "4.1.2",
"#angular/platform-browser-dynamic": "4.1.2",
"#angular/platform-server": "4.1.2",
"#angular/router": "4.1.2",
"#types/node": "7.0.18",
"angular2-template-loader": "0.6.2",
"aspnet-prerendering": "^2.0.5",
"aspnet-webpack": "^1.0.29",
"awesome-typescript-loader": "3.1.3",
"bootstrap": "3.3.7",
"css": "2.2.1",
"css-loader": "0.28.1",
"es6-shim": "0.35.3",
"event-source-polyfill": "0.0.9",
"expose-loader": "0.7.3",
"extract-text-webpack-plugin": "2.1.0",
"file-loader": "0.11.1",
"html-loader": "0.4.5",
"isomorphic-fetch": "2.2.1",
"jquery": "3.2.1",
"json-loader": "0.5.4",
"preboot": "4.5.2",
"raw-loader": "0.5.1",
"reflect-metadata": "0.1.10",
"rxjs": "5.4.0",
"style-loader": "0.17.0",
"to-string-loader": "1.1.5",
"typescript": "2.3.2",
"url-loader": "0.5.8",
"webpack": "2.5.1",
"webpack-hot-middleware": "2.18.0",
"webpack-merge": "4.1.0",
"zone.js": "0.8.10"
},
"devDependencies": {
"#types/chai": "3.5.2",
"#types/jasmine": "2.5.47",
"chai": "3.5.0",
"istanbul-instrumenter-loader": "^3.0.0",
"jasmine-core": "2.6.1",
"karma": "1.7.0",
"karma-chai": "0.1.0",
"karma-chrome-launcher": "2.1.1",
"karma-cli": "1.0.1",
"karma-coverage-istanbul-reporter": "^1.3.0",
"karma-htmlfile-reporter": "^0.3.5",
"karma-jasmine": "1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-phantomjs-launcher": "^1.0.4",
"karma-webpack": "2.0.3",
"phantomjs-prebuilt": "^2.1.15"
}`
and the tsconfig.json is as follows:
`{
"compilerOptions": {
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
"lib": [ "es6", "dom" ],
"types": [ "node" ]
},
"exclude": [
"bin",
"node_modules"
],
"atom": { "rewriteTsconfig": false }
}`
and the webpack.config.js code is :
`const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
context: __dirname,
resolve: {
extensions: ['.js', '.ts'],
modules: [path.join(__dirname, "node_modules")]
},
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = '..//wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': '..//ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('..//wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
};
`
How can i solve the errors mentioned above? I have tried solutions mentioned in https://github.com/monounity/karma-typescript/issues/83. Nothing worked.
Any help would be appreciated!
Looking forward for some answer.
Thanks.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~``
Solution to include chrome headless:
included "puppeteer" in package.json under dev dependencies.
Configured in Karma.config.js:
const ChromiumRevision = require('puppeteer/package.json').puppeteer.chromium_revision;
const Downloader = require('puppeteer/utils/ChromiumDownloader');
const revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), ChromiumRevision);
module.exports = function (config) {
config.set({ ...
browsers: ['ChromeHeadless'],
..
});
};

phantomJS and run the tests, but i get the following errors:
PhantomJS is old and doesn't support ES6 features like Map. You can try to get it to work with core-js but you are essentially trying to lift a dead tech to modern standards.
More
The replacement for phantomjs is chrome headless.

Related

Getting 404 on angular application load

I have upgraded my angular application from version 12 to 14. I'm using custom Webpack. In MVC view I have added the main.js script. But on page load I'm getting 404 for all the HTML & CSS pages. I need to generate 2 output files main.js & main.bo.js. Based on the user role I'm loading corresponding MVC page. One view is for front end application where I'm registering main.js & another view is for back office where I'm registering main.bo.js.
When the application is loading I'm getting 404 for all the html pages & css.
Tried many options but not able to resolve the issue. Any help will be appreciated.
Error Details
I'm using custom webpack because I need 2 entry point main.js and main.bo.bundle.js. Based on the creds I'm registering either main.js or main.bundle.bo in my mvc application.
This is how I'm registering script from MVC view.
Scripts
Wepback.config.js
"use strict";
const path = require('path');
const webpack = reiuire('webpack');
const CssMinimizer = require('css-minimizer-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
mode: "development", // "production" | "development" | "none"
entry: {
//'polyfills': './angular/src/polyfills.ts',
'vendor': './angular/src/vendor.ts',
'app': './angular/src/main.ts',
'bo': './angular/src/main.bo.ts'
},
output: {
path: path.resolve(__dirname, '../dist'),
filename: '[name].bundle.js',
libraryTarget: 'umd',
clean: true
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: 'babel-loader',
options: {
plugins: ['#angular/compiler-cli/linker/babel'],
compact: false,
cacheDirectory: true,
}
}
},
{
test: /src\/.*\.js$/,
use: [
{
loader: 'babel-loader',
options: {
sourceMaps: false,
cacheDirectory: true,
cacheCompression: false
}
},
...(
[{ loader: 'source-map-loader' }]
)
],
exclude: [/(node_modules|bower_components)/]
},
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
onlyCompileBundledFiles: true
}
}
],
exclude: [/node_modules/, /test/]
},
{
test: /\.(html)$/,
use: 'html-loader'
},
{
test: /src\/app\/.*\.css$/,
use: [
'style-loader',
'css-loader'
]
},
]
},
resolve: {
extensions: ['.mjs', '.ts', '.js', '.css', '.html'],
fallback: {
crypto: "crypto-browserify",
http: "stream-http",
https: "https-browserify",
os: "os-browserify/browser",
path: "path-browserify",
stream: "stream-browserify",
process: "process/browser",
zlib: "browserify-zlib",
url: "url/",
},
},
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000
},
devtool: 'source-map',
target: "web",
plugins: [
new webpack.ContextReplacementPlugin(
/\#angular(\\|\/)core(\\|\/)esm5/,
'./angular',
{}
),
new MiniCssExtractPlugin(),
new HtmlWebpackPlugin(),
new webpack.SourceMapDevToolPlugin({
filename: '[name].js.map',
exclude: ['vendor.ts']
})
],
optimization: {
minimize: false,
minimizer: [
new TerserPlugin({
exclude: /assets/,
extractComments: false
})
]
}
}
Package.json
"devDependencies": {
"#angular-builders/custom-webpack": "^14.0.0",
"#angular-builders/dev-server": "^7.3.1",
"#angular-devkit/build-angular": "^14.0.0",
"#angular/cli": "^14.0.0",
"#angular/compiler-cli": "^14.0.0",
"#babel/plugin-proposal-decorators": "^7.18.9",
"#ngtools/webpack": "11.0.7",
"#types/jasmine": "~4.0.0",
"#types/jest": "^27.4.1",
"#webpack-cli/serve": "^1.6.1",
"babel-loader": "^8.2.5",
"css-loader": "^5.2.7",
"css-minimizer-webpack-plugin": "^4.0.0",
"extract-text-webpack-plugin": "^2.1.0",
"file-loader": "^6.2.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^5.5.0",
"jasmine-core": "~4.1.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-html-detailed-reporter": "^1.1.20",
"karma-jasmine": "~5.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"karma-phantomjs-launcher": "^1.0.4",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.4",
"lodash": "^4.17.21",
"mini-css-extract-plugin": "^2.6.1",
"phantomjs": "^1.9.19",
"raw-loader": "^4.0.2",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.3.3",
"to-string-loader": "^1.2.0",
"ts-loader": "^9.3.1",
"typescript": "~4.7.2",
"uglifyjs-webpack-plugin": "^1.1.2",
"url": "^0.11.0",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3",
"webpack-merge": "^5.8.0"
},
"dependencies": {
"#angular/animations": "^14.0.0",
"#angular/cdk": "^14.0.0",
"#angular/cli": "14.0.0",
"#angular/common": "^14.0.0",
"#angular/compiler": "^14.0.0",
"#angular/core": "^14.0.0",
"#angular/forms": "^14.0.0",
"#angular/material": "^14.0.0",
"#angular/platform-browser": "^14.0.0",
"#angular/platform-browser-dynamic": "^14.0.0",
"#angular/router": "^14.0.0",
"#babel/core": "^7.18.9",
"#babel/preset-env": "^7.18.9",
"#ng-idle/core": "^11.1.0",
"#ng-idle/keepalive": "^11.0.3",
"#types/node": "14.17.3",
"#types/webrtc": "^0.0.30",
"angular2-template-loader": "^0.6.2",
"assert": "^2.0.0",
"browserify-zlib": "^0.2.0",
"canvg": "^3.0.7",
"classlist.js": "^1.1.20150312",
"codelyzer": "^0.0.28",
"core-js": "^3.23.5",
"crypto-browserify": "^3.12.0",
"enhanced-resolve": "3.3.0",
"font-awesome": "^4.7.0",
"html2canvas": "1.0.0-alpha.9",
"https-browserify": "^1.0.0",
"ie-shim": "^0.1.0",
"jspdf": "^2.4.0",
"ng2-material-dropdown": "^0.11.0",
"ng2-pdf-viewer": "^3.0.8",
"ngx-bootstrap": "^6.2.0",
"ngx-toastr": "^14.2.1",
"node": "^18.5.0",
"node-fetch": "^2.6.1",
"oidc-client": "^1.10.1",
"os-browserify": "^0.3.0",
"pdfjs-dist": "^2.14.305",
"primeng": "^14.0.0-rc.1",
"rxjs": "~7.5.0",
"rxjs-compat": "^6.6.7",
"rxjs-tslint": "^0.1.8",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"tsconfig-paths-webpack-plugin": "^4.0.0",
"tslib": "^2.3.0",
"typescript-base64-arraybuffer": "^0.1.0",
"web-animations-js": "^2.3.1",
"yarn": "^1.22.17",
"zone.js": "^0.10.3"
},
"-vs-binding": {
"ProjectOpened": [
"test"
]
},
"browser": {
"zlib": false
}
TSConfig -
{
"compileOnSave": false,
"buildOnSave": false,
"compilerOptions": {
"baseUrl": "./",
// "outDir": "./dist",
// "forceConsistentCasingInFileNames": false,
"strict": false,
//"noImplicitOverride": true,
//"noPropertyAccessFromIndexSignature": true,
//"noImplicitReturns": false,
"noImplicitAny": false,
"strictPropertyInitialization": false,
//"noFallthroughCasesInSwitch": true,
"strictNullChecks": false,
"sourceMap": true,
"declaration": false,
//"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
//"importHelpers": true,
"target": "es5",
"module": "esnext",
"lib": [
"ES6",
"dom"
],
"paths" : {
"crypto": ["./node_modules/crypto-browserify"],
"stream": ["./node_modules/stream-browserify"],
"assert": ["./node_modules/assert"],
"http": ["./node_modules/stream-http"],
"https": ["./node_modules/https-browserify"],
"os": ["./node_modules/os-browserify"],
"zlib": ["./node_modules/browserify-zlib"]
},
},
"angularCompilerOptions": {
"compilationMode": "partial"
}
}
Index.html file from dist folder.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webpack App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"><script defer src="vendor.bundle.js"></script><script defer src="app.bundle.js"></script><script defer src="bo.bundle.js"></script></head>
<body>
</body>
</html>

How do I configure webpack to display react component with typescript

So I'm trying to get my node project to render a simple react component, I'm using webpack for bundling
my package.json set's main entry point as webpack.config.js and has a srcipt to run webpack-dev-server. Here is my package.json :
{
"name": "#ruler-mobility/ruler",
"_comment": "main set to webpack's bundle file(home.tsx). this attr only explain main's purpose, delete it in the next merge ",
"main": "webpack.config.js",
"dependencies": {
"#types/jest": "^25.1.3",
"axios": "^0.19.1",
"chalk": "^3.0.0",
"compression": "^1.7.4",
"cors": "^2.8.5",
"errorhandler": "^1.5.1",
"express": "^4.17.1",
"express-session": "^1.16.2",
"geolocation-utils": "^1.2.2",
"jest": "^25.1.0",
"jsonwebtoken": "^8.5.1",
"node-sass": "^4.13.1",
"numeral": "^2.0.6",
"query-string": "^6.11.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"ts-jest": "^25.2.1",
"typecast": "0.0.1",
"winston": "^3.2.1"
},
"devDependencies": {
"#types/compression": "^1.0.1",
"#types/concurrently": "^4.1.0",
"#types/cors": "^2.8.6",
"#types/errorhandler": "^0.0.32",
"#types/express": "^4.17.1",
"#types/express-session": "^1.15.14",
"#types/jsonwebtoken": "^8.3.6",
"#types/node": "^12.12.25",
"#types/numeral": "0.0.26",
"#types/react": "^16.9.23",
"#types/react-dom": "^16.9.5",
"#types/ts-nameof": "^4.2.1",
"#types/winston": "^2.4.4",
"#typescript-eslint/eslint-plugin": "^2.18.0",
"#typescript-eslint/parser": "^2.18.0",
"cache-loader": "^4.1.0",
"concurrently": "^5.0.0",
"dotenv-webpack": "^1.7.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.9.0",
"eslint-config-standard": "^14.1.0",
"eslint-import-resolver-typescript": "^2.0.0",
"eslint-loader": "^3.0.3",
"eslint-plugin-autofix": "0.0.9",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-no-use-extend-native": "^0.4.1",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.18.0",
"eslint-plugin-react-hooks": "^1.7.0",
"eslint-plugin-sonarjs": "^0.5.0",
"eslint-plugin-sort-imports-es6-autofix": "^0.5.0",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-switch-case": "^1.1.2",
"fork-ts-checker-webpack-plugin": "^4.0.4",
"jest-extended": "^0.11.4",
"nodemon": "^1.19.2",
"prettier": "^1.19.1",
"ts-loader": "^6.2.1",
"ts-nameof": "^4.2.2",
"ts-node": "^8.6.2",
"tsconfig-paths-webpack-plugin": "^3.2.0",
"typescript": "^3.7.5",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.3",
"webpack-merge": "^4.2.2",
"webpack-node-externals": "^1.7.2"
},
"repository": {
"type": "git",
"url": "git+https://bitbucket.org/ruler-mobility/ruler.git"
},
"scripts": {
"start": "webpack-dev-server",
"build": "webpack --mode=production",
"lint": "eslint . --quiet --fix --ext js,jsx,ts,tsx",
"test": "jest --forceExit --coverage --verbose",
"watch-test": "npm run test -- --watchAll",
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"
},
"version": "1.0.0"
}
my webpack.config.js sets Home.tsx as entry point for the what to bundle and the output file's path in a parent folder. here is how it looks:
const path = require('path');
const chalk = require('chalk');
const merge = require('webpack-merge');
const Dotenv = require('dotenv-webpack');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const tsNameof = require('ts-nameof');
const { PORT } = process.env;
module.exports = (env = {}, argv = {}) => {
const { mode } = argv;
const production = mode === 'production';
const development = !production;
console.log(
chalk.blue(`The current build process is running in ${chalk.underline((production ? 'production' : 'development').toUpperCase())} mode`)
);
return merge(
{
devtool: production ? 'eval' : 'cheap-module-eval-source-map'
},
development && {
optimization: {
removeAvailableModules: false,
removeEmptyChunks: false,
splitChunks: false
},
output: {
pathinfo: false
}
},
{
context: __dirname,
target: 'node',
externals: [nodeExternals()],
//set the entry point to our app(the front-end)
entry: path.resolve(__dirname, './front-end/components/Home.tsx'),
module: {
rules: [
{
test: /\.tsx?$/,
use: [
'cache-loader',
{
loader: 'ts-loader',
options: {
transpileOnly: true,
happyPackMode: true
}
},
{
loader: 'eslint-loader',
options: {
fix: true,
quiet: true,
// eslint-disable-next-line #typescript-eslint/explicit-function-return-type
getCustomTransformers: () => ({ before: [tsNameof] })
}
}
],
exclude: /node_modules/
}
]
},
plugins: [new Dotenv(), new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true })],
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
plugins: [
new TsconfigPathsPlugin({
configFile: 'tsconfig.json'
})
]
},
// output set's the path for front-end bundle file
output: {
path: path.resolve(__dirname, 'front-end/dist'),
filename: 'home.js'
},
devServer: {
contentBase: path.join(__dirname, 'front-end/dist'),
compress: true,
open: true,
hot: true,
port: PORT || 3000
}
}
);
};
So I expect webpack to bundle my files(which will include everything my Home.tsx uses) in the front-end/dist directory under the name home.js
here is how I setup my Home. I have a index html at the path front-end/index.html that contains:
<body>
<div class="container"></div>
<h1>Hello</h1>
<script src="/front-end/dist/home.js"></script>
</body>
AND my Home.jsx:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const ROOT = document.querySelector('.container');
ReactDOM.render(<h1>HELLO 2</h1>, ROOT);
When I run npm run script start and open localhost:3000, I get my browser showing me all the files in the front-end/dist directory, which is the home.js file. Shouldn't it load the Home.tsx file because that is what I have set as the entry point in webpack. How do I configure webpack to display 'home.tsx' at the root i.e localhost:3000.
plus here my tsconfig file:
{
"compilerOptions": {
"alwaysStrict": true,
"module": "commonjs",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"jsx": "react",
"lib": ["es6", "dom"],
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"],
"#ruler": ["src", "packages"],
"#ruler/*": ["src/*", "packages/*"],
"#ruler/configs": ["configs"],
"#ruler/configs/*": ["configs/*"],
"#ruler/test": ["test"],
"#ruler/test/*": ["test/*"],
"#ruler/types": ["types"],
"#ruler/types/*": ["types/*"]
}
},
"exclude": ["node_modules", "**/*.spec.ts"]
}
file structure:
Project
|
+-- package.json
|
+-- tsconfig.json
|
+-- webpack.config.js
|
+-- front-end
| |
+-- components
| |
| +-- Home.tsx
|
+--index.html
Note: these are only the files used for the set-up, the project consists of more but I don't they're needed to be mentioned
It looks to me that you are referring to a wrong file. Because you have mentioned a .tsx file but your actual file is a .jsx file. So i feel you should add .jsx instead:
entry: path.resolve(__dirname, './front-end/components/Home.jsx')
or you should rename your file to Home.tsx.
First of all if you need to add typescript support to your webpack config you need to add '.ts' and '.tsx' as resolvable extensions abd add a specific loader rule for ts files support.
resolve: {
extensions: [".ts", ".tsx"]
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
},
your home.js is the bundled file generated by webpack as an output after transpiling your entry file which will be either your Home.jsx or your Home.tsx.

Webpack css-loader does not resolve aliases

Currently doing maintenance for a project that was running React v15. Upgraded Webpack 3 > 4, Babel 6 > 7, css-loader 0.28.x > 3.0.0, etc.
Initially, updated React and used all the react-codemod + jscodeshift to transform the js files. While the version at that stage was not stable, it loaded and showed the proper styles etc.
What I find odd, is that after updating file-loader, css-loader, babel, and related packages, I kept getting Module not found: Error: Can't resolve, as following:
ERROR in ./app/sharedComponents/TitleGeneric/style.css (./node_modules/css-loader/dist/cjs.js??ref--6-1!./app/sharedComponents/TitleGeneric/style.css)
Module not found: Error: Can't resolve './sharedStyles/typography.css' in '/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric'
resolve './sharedStyles/typography.css' in '/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric'
using description file: /Users/userX/www/my-project-ui/package.json (relative path: ./app/sharedComponents/TitleGeneric)
Field 'browser' doesn't contain a valid alias configuration
using description file: /Users/userX/www/my-project-ui/package.json (relative path: ./app/sharedComponents/TitleGeneric/sharedStyles/typography.css)
no extension
Field 'browser' doesn't contain a valid alias configuration
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.wasm doesn't exist
.mjs
Field 'browser' doesn't contain a valid alias configuration
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.mjs doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.json doesn't exist
as directory
/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css doesn't exist
[/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css]
[/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.wasm]
[/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.mjs]
[/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.js]
[/Users/userX/www/my-project-ui/app/sharedComponents/TitleGeneric/sharedStyles/typography.css.json]
# ./app/sharedComponents/TitleGeneric/style.css (./node_modules/css-loader/dist/cjs.js??ref--6-1!./app/sharedComponents/TitleGeneric/style.css) 5:10-107 12:44-141
# ./app/sharedComponents/TitleGeneric/style.css
# ./app/sharedComponents/TitleGeneric/TitleGeneric.js
# ./app/pages/Knowledge/Bricks/Bricks.js
# ./app/pages/Knowledge/Bricks/BricksContainer.js
# ./app/loaders/pages.js
# ./app/router/routes.js
# ./app/index.js
# multi core-js/stable ./app
Before posting I've done a lot of testing, trying and seeing, modified a lot of code and could not figure out the issue; I've also done quite a lot of research online. Finally checked if there are any posts about this in StackOverflow, which I believe there is not at the moment.
Here's the package.json file:
{
"name": "Foobar",
"version": "1.0.0",
"main": "index.js",
"scripts": {
...
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [],
"license": "ISC",
"engines": {
"node": ">=8.12.0"
},
"nyc": {
"include": [
"app/**/*.js"
],
"require": [
"#babel/register"
],
"all": "true",
"cache": "true",
"reporter": [
"text",
"html"
],
"sourceMap": "false",
"instrument": "false"
},
"dependencies": {
"#babel/core": "^7.5.0",
"#babel/plugin-proposal-class-properties": "^7.5.0",
"#babel/preset-env": "^7.5.3",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.4.4",
"#moola/moola-component-library": "^0.3.9",
"#moola/moola-nuka-carousel": "^2.0.4-2",
"axios": "^0.15.3",
"babel-eslint": "^10.0.2",
"babel-loader": "^8.0.6",
"babel-plugin-lodash": "^3.3.4",
"bootstrap": "^3.3.7",
"highcharts": "^4.2.6",
"highcharts-more": "^0.1.2",
"intl": "^1.2.5",
"js-cookie": "^2.1.3",
"jwt-decode": "^2.1.0",
"mime-types": "^2.1.12",
"npm": "^5.8.0",
"numeral": "^1.5.3",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-addons-create-fragment": "^15.6.0",
"react-bootstrap": "^0.30.8",
"react-dom": "^16.8.6",
"react-highcharts": "^16.0.2",
"react-highstock": "^1.0.2",
"react-intl": "^2.4.0",
"react-intl-redux": "^2.1.1",
"react-markdown-renderer": "^1.4.0",
"react-modal": "3.8.2",
"react-paginate": "^5.2.2",
"react-redux": "^5.1.1",
"react-router-redux": "^4.0.7",
"react-transition-group": "^2.1.0",
"redux": "^4.0.1",
"redux-debounced": "^0.5.0",
"redux-form": "^7.4.2",
"redux-segment": "^1.6.1",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"#babel/plugin-proposal-export-default-from": "^7.5.2",
"acorn": "^6.2.0",
"add-asset-html-webpack-plugin": "^3.1.3",
"autoprefixer": "^9.6.1",
"babel-plugin-module-resolver": "^3.2.0",
"chai": "^3.5.0",
"chalk": "^1.1.3",
"core-js": "^3.1.4",
"create-react-class": "^15.6.3",
"css-loader": "^3.0.0",
"cyclist": "^1.0.1",
"enzyme": "^2.9.1",
"es6-promise": "^4.1.0",
"eslint": "^6.0.1",
"eslint-config-standard": "^13.0.0-1 ",
"eslint-plugin-import": "^2.18.0",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-standard": "^4.0.0",
"express": "^4.16.4",
"extract-loader": "^3.1.0",
"file-loader": "^4.0.0",
"git-revision-webpack-plugin": "^2.4.0",
"html-webpack-plugin": "^3.2.0",
"html2plaintext": "^2.0.1",
"husky": "^0.11.9",
"jsdom": "^9.4.1",
"json-server": "^0.14.0",
"jspolyfill-array.prototype.find": "^0.1.3",
"jspolyfill-array.prototype.findIndex": "^0.1.0",
"leasot": "^4.7.1",
"lodash-webpack-plugin": "^0.11.5",
"mini-css-extract-plugin": "^0.7.0",
"mocha": "^2.5.3",
"mocha-jenkins-reporter": "^0.2.3",
"mock-css-modules": "^1.0.0",
"moment": "^2.22.2",
"postcss-loader": "^3.0.0",
"postcss-modules-values": "^1.3.0",
"randexp": "^0.5.3",
"react-test-renderer": "^16.8.6",
"sinon": "^1.17.4",
"string-replace-webpack-plugin": "^0.1.3",
"style-loader": "^0.23.1",
"url-loader": "^2.0.1",
"webpack": "^4.35.3",
"webpack-bundle-analyzer": "^1.4.1",
"webpack-cli": "^3.3.5",
"webpack-dev-middleware": "^2.0.6",
"webpack-dev-server": "^2.9.1",
"webpack-hot-middleware": "^2.22.1",
"webpack-merge": "^4.1.0",
"webpack-s3-plugin": "0.9.0"
},
"optionalDependencies": {
"fsevents": "*"
}
}
The webpack base configuration file:
const webpack = require('webpack')
const path = require('path')
const chalk = require('chalk')
const loaderRules = require('./loaders')
const setup = require('./setup')
const PATHS = setup.PATHS
const VALUES = setup.VALUES
const HtmlWebpackPlugin = require('html-webpack-plugin')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const IgnorePlugin = require('webpack/lib/IgnorePlugin')
const LodashReplacePlugin = require('lodash-webpack-plugin')
const isDev = process.env.npm_lifecycle_event !== 'vendor:production'
// Base configuration
const { analyticsKey, applicationPath, htmlLinkPath } = VALUES
let vendorManifest
try {
vendorManifest = require(path.join(PATHS.build, 'vendor.json'))
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e
}
/* eslint-disable no-console */
console.log(chalk.red('*** Moo.la script error ***'))
console.log(chalk.red('Vendor bundle/manifest not found.\nPlease run ') +
chalk.white('`npm run vendor`') +
chalk.red(' first to generate it, then try again.'))
/* eslint-enable no-console */
process.exit(1)
}
let plugins = [
new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: vendorManifest,
}),
new HtmlWebpackPlugin({
analyticsKey,
template: path.join(PATHS.app, 'shell', 'index.html'),
filename: 'index.html',
inject: 'body',
applicationPath,
htmlLinkPath,
}),
new AddAssetHtmlPlugin({
filepath: path.join(PATHS.build, 'vendor.dll.js'),
includeSourcemap: false,
}),
new IgnorePlugin(/^\.\/locale$/, /moment$/),
new LodashReplacePlugin(),
new webpack.DefinePlugin({
CDN_URL: JSON.stringify(VALUES.baseCdnUrl),
}),
]
const baseConfig = {
entry: {
index: ['core-js/stable', PATHS.app],
},
plugins,
resolve: {
modules: [
PATHS.app,
'node_modules',
],
alias: {
videos: path.resolve(__dirname, '../app/videos/'),
sharedStyles: path.resolve(__dirname, '../app/sharedStyles/'),
images: path.resolve(__dirname, '../app/images/'),
animated: path.resolve(__dirname, '../app/animated/'),
}
},
module: {
rules: loaderRules,
},
optimization: {
namedModules: true,
splitChunks: {
chunks: "all"
},
runtimeChunk: true,
concatenateModules: true,
},
output: {
path: PATHS.build,
filename: '[name]_bundle.js',
chunkFilename: '[name]_chunk.js',
},
}
module.exports = baseConfig
I've also tried to add a plugin to resolve from Babel, but without much luck:
{
"presets": [
["#babel/preset-env", {
"targets": {
"ie": 11
},
"modules": false
}],
"#babel/preset-react",
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-export-default-from",
["module-resolver", {
"root": ["./app"],
"alias": {
"videos": "./app/videos/",
"sharedStyles": "./app/sharedStyles/",
"images": "./app/images/",
"animated": "./app/animated/"
}
}]
]
}
The application is launched by node server.js where server.js looks like (simplified):
const port = 8080
const path = require('path')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const webpackConfigLocal = require('../webpack/config.local')
...
app.use(bodyParser.json())
router.use(webpackDevMiddleware(compiler, {
publicPath: '/',
logLevel: 'debug',
stats: {
colors: true,
hash: false,
version: true,
timings: false,
assets: false,
chunks: false,
modules: false,
reasons: false,
children: false,
source: false,
errors: true,
errorDetails: true,
warnings: true,
publicPath: false,
},
}))
router.use(webpackHotMiddleware(compiler))
...
app.listen(port, () => console.log(`Development server listening on port ${port}`))
I'm running out of ideas and might have to revert Webpack, Babel and all related plugins and packages back to the previous version instead.
I wonder if there is someone out there who might spot what's wrong or provide any hints or ideas on how to fix this!
Thank you!
I got back to this issue and noticed that at some point past 0.28.x css-loader requires the prefix ~ for aliases.
Find "To import styles from a node_modules path (include resolve.modules) and for alias, prefix it with a ~" in https://github.com/webpack-contrib/css-loader

Can't resolve 'react-hot-loader/webpack'

I've been stuck with this for a while trying to install and update. Finally, all the npm packages are in the latest version. Could you please let me know how I could get past this blocking error?
[ERROR] ERROR in multi react-hot-loader/patch event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.tsx
Module not found: Error: Can't resolve 'react-hot-loader/webpack' in '...'
# multi react-hot-loader/patch event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.tsx
Here's my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'main': './ClientApp/boot.tsx' },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: 'dist/'
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader"
}
]
},
plugins: [
new CheckerPlugin(),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.css')
])
}];
};
Here is the package.json so that the versions of the packages that I'm using are shown below:
{
"name": "MyProject",
"private": true,
"version": "0.0.0",
"devDependencies": {
"#types/history": "4.6.2",
"#types/react": "^16.4.1",
"#types/react-dom": "16.0.6",
"#types/react-hot-loader": "4.1.0",
"#types/react-router": "4.0.27",
"#types/react-router-dom": "4.2.7",
"#types/react-table": "^6.7.11",
"#types/webpack-env": "1.13.6",
"aspnet-webpack": "^3.0.0",
"aspnet-webpack-react": "^3.0.0",
"awesome-typescript-loader": "5.2.0",
"bootstrap": "4.1.1",
"css-loader": "0.28.11",
"event-source-polyfill": "0.0.12",
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "1.1.11",
"isomorphic-fetch": "2.2.1",
"jquery": "3.3.1",
"json-loader": "0.5.7",
"react": "16.4.1",
"react-dom": "^16.4.1",
"react-hot-loader": "^4.3.3",
"react-router-dom": "4.3.1",
"style-loader": "0.21.0",
"typescript": "2.9.2",
"url-loader": "1.0.1",
"webpack": "^4.12.2",
"webpack-dev-middleware": "^3.1.3",
"webpack-dev-server": "^3.1.4",
"webpack-hot-middleware": "^2.22.2"
},
"dependencies": {
"#types/react-fontawesome": "^1.6.3",
"ajv": "^6.5.1",
"classnames": "^2.2.6",
"font-awesome": "^4.7.0",
"get-latest": "^0.1.0",
"latest-version": "^4.0.0",
"npm": "^6.1.0",
"npm-install-peers": "^1.2.1",
"popper.js": "^1.14.3",
"react-table": "^6.8.6",
"update-all-packages": "^1.0.2"
}
}

State of the art webpack / React configuration

I'm trying to setup a webpack 2, babel, and React configuration for achieving:
Native ES6/ES7 features
Tree shaking builds
Hot reloading
I had a demo repo but it has distinct stuff mixed, like even JSHint and ESLint at the same time.
I'd like to get my setup up and running and get suggestions for best practices
So, as first option I tried to use babel-preset-env. Then after some dependencies being installed. I ran into this issue:
ERROR in ./src/main.jsx
Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level (3:0)
However, the first line in my code is import 'babel-polyfill'; then just import's.
This is how my Babel config file looks like:
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": ["last 2 versions"]
}
}
],
"react"
],
"plugins": [
"babel-plugin-transform-class-properties",
"transform-react-require"
]
}
This is what my development webpack config file looks like:
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const config = {
//Entry points to the project
entry: [
'babel-polyfill',
'webpack/hot/dev-server',
'webpack/hot/only-dev-server',
path.join(__dirname, '../src/main.jsx')
],
//Config options on how to interpret requires imports
resolve: {
extensions: [".js", ".jsx"]
},
//Server Configuration options
devServer:{
contentBase: 'build', //Relative directory for base of server
devtool: 'eval',
hot: true, //Live-reload
inline: true,
port: 3000, //Port Number
host: 'localhost', //Change to '0.0.0.0' for external facing server
proxy: {
'^\/api': {
target: 'http://127.0.0.1:9090'
}
},
historyApiFallback: true
},
devtool: 'eval',
output: {
path: buildPath, //Path of output file
filename: 'app.js'
},
plugins: [
new webpack.DefinePlugin({
API_BASE: '""',
PRODUCTION: false,
'process.env.NODE_ENV': '"development"'
}),
//Enables Hot Modules Replacement
new webpack.HotModuleReplacementPlugin(),
//Allows error warnings but does not stop compiling. Will remove when eslint is added
new webpack.NoEmitOnErrorsPlugin(),
//Moves files
new TransferWebpackPlugin([
{from: 'www'}
], path.resolve(__dirname, "src")),
new ExtractTextPlugin("main.css")
],
module: {
rules: [
{
//React-hot loader and
test: /\.(js|jsx)$/, //All .js and .jsx files
loaders: [ 'babel-loader', 'react-hot-loader'],
//react-hot is like browser sync and babel loads jsx and es6-7
exclude: [nodeModulesPath]
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style',
use: 'css'
})
},
{
test: /\.svg$/,
loader: 'svg-sprite?' + JSON.stringify({
name: '[name]_[hash]',
prefixize: true
})
}
]
}
};
module.exports = config;
And this below is package.json
{
"name": "LumaHealth",
"version": "1.0.0",
"description": "LumaHealth",
"main": "start.js",
"scripts": {
"start": "webpack --config ./webpack/webpack.config.development.js",
"build": "webpack --config ./webpack/webpack.config.production.js",
"clean": "rm build/app.js"
},
"repository": {
"type": "git",
"url": "git#github.com:lumahealthhq/web-app.git"
},
"keywords": [],
"author": "Marcelo Oliveira",
"license": "MIT",
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-core": "^6.24.0",
"babel-eslint": "^7.2.1",
"babel-plugin-react-require": "^3.0.0",
"babel-plugin-transform-class-properties": "^6.23.0",
"babel-preset-env": "^1.2.2",
"babel-preset-react": "^6.23.0",
"css-loader": "^0.26.4",
"enzyme": "^2.0.0",
"eslint": "^3.7.1",
"eslint-config-airbnb": "^14.1.0",
"eslint-loader": "^1.7.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.4.1",
"extract-text-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "^2.28.0",
"nyc": "^10.1.2",
"postcss-loader": "^1.3.3",
"postcss-nested": "^1.0.0",
"react-addons-test-utils": "^15.4.1",
"sinon": "^1.17.2",
"style-loader": "^0.13.2",
"sw-precache": "^5.0.0",
"transfer-webpack-plugin": "^0.1.4",
"webpack": "^2.3.2",
"webpack-dev-server": "^2.4.2"
},
"dependencies": {
"babel-core": "^6.5.2",
"babel-eslint": "^7.0.0",
"babel-plugin-transform-react-require": "^1.0.1",
"babel-polyfill": "^6.23.0",
"co": "^4.6.0",
"express": "^4.12.3",
"file-loader": "^0.10.1",
"humps": "^2.0.0",
"isomorphic-fetch": "^2.2.1",
"local-storage": "^1.4.2",
"lodash": "^4.16.4",
"material-ui": "^0.17.0",
"moment": "^2.15.2",
"q": "^1.4.1",
"react": "^15.4.1",
"react-dom": "^15.4.1",
"react-redux": "^5.0.3",
"react-router": "^3.0.2",
"react-router-redux": "^4.0.6",
"react-slick": "^0.14.4",
"react-tap-event-plugin": "^2.0.0",
"react-web-notification": "^0.2.3",
"redux": "^3.6.0",
"redux-form": "^6.1.1",
"redux-logger": "^2.7.0",
"redux-socket.io": "^1.3.1",
"redux-thunk": "^2.1.0",
"socket.io-client": "^1.7.2",
"url-loader": "^0.5.7",
"vanilla-masker": "^1.0.9"
}
}
I recently upgraded my boilerplate from webpack 1 to webpack 2, feel free to get any information / concept from the webpack config file there, hope it helps.
https://github.com/iroy2000/react-redux-boilerplate

Resources