Webpack is throwing lots of errors from node modules when running watch-development - vue.js

When running watch-development I am plagued with so many errors from my node modules and I'm not sure where to begin to even resolve some of them. Maybe something is wrong with my webpack configuration but I have tried looking for a solution for days now and have found nothing
Some of the errors:
TS2307: Cannot find module 'rxjs-compat/operators/multicast'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\observeOn.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\observeOn.ts(1,15)
TS2307: Cannot find module 'rxjs-compat/operators/observeOn'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\onErrorResumeNext.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\onErrorResumeNext.ts(1,15)
TS2307: Cannot find module 'rxjs-compat/operators/onErrorResumeNext'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\pairwise.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\pairwise.ts(1,15)
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(37,3)
TS2552: Cannot find name 'expect'. Did you mean 'expected'?
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(40,1)
TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(42,3)
TS2304: Cannot find name 'expect'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(45,3)
I have hundreds of errors like this all coming from my node modules, Mostly complaining it can't find a module, but also some complaining it cannot find name 'x'
this is my webpack config:
/// <binding />
"use strict";
module.exports = (env, options) => {
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoader = require("vue-loader");
let pathsToClean = ['dist/*.*', 'dist/fonts/*.*', 'dist/images/*.*'];
let cleanOptions = {
root: __dirname + '/wwwroot/',
verbose: true,
dry: false
};
return {
mode: 'development',
entry: {
app: './wwwroot/VueApp/Home/app.ts',
mainCss: './wwwroot/VueApp/CSS/site.scss'
},
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin(pathsToClean, cleanOptions),
new webpack.ProvidePlugin({
Popper: ['popper.js', 'default'],
moment: 'moment',
vueResource: 'vue-resource',
vueRouter: 'vue-router',
vuex: 'vuex'
}),
new VueLoader.VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].bundle.css"
})
],
output: {
publicPath: "/dist/",
path: path.join(__dirname, '/wwwroot/dist/'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
query: {
presets: [
['env', { targets: { uglify: true } }]
]
}
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { minimize: true, sourceMap: false } },
{
loader: 'sass-loader', options: { sourceMap: false } }
],
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: './images/[name].[ext]'
}
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: './fonts/[name].[ext]'
}
}
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
resolve: {
alias: {
vue: 'vue/dist/vue.js'
},
extensions: ['.ts', '.js', '.vue', '.json']
}
};
};
this is what my file structure looks like:
https://ibb.co/xjQMCX0

Related

Cannot build react-native project for web that uses #sentry/react-native and react-native-web

The existing configuration for compilation seems to have issues compiling some syntax used in sentry source code. The screenshot shows two places where the exception occurs.
Here is the configuration used
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const appDirectory = path.resolve(__dirname, '../')
// This is needed for webpack to compile JavaScript.
// Many OSS React Native packages are not compiled to ES5 before being
// published. If you depend on uncompiled packages they may cause webpack build
// errors. To fix this webpack can be configured to compile to the necessary
// `node_module`.
const babelLoaderConfiguration = {
test: /\.js$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(appDirectory, 'index.web.js'),
path.resolve(appDirectory, 'src'),
path.resolve(appDirectory, 'prebundled'),
path.resolve(appDirectory, 'node_modules/react-native')
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: ['module:metro-react-native-babel-preset'],
// Re-write paths to import only the modules needed by the app
plugins: [
'react-native-web',
[
'module-resolver',
{
alias: {
'^react-native$': 'react-native-web'
}
}
]
]
}
}
}
// This is needed for webpack to import static images in JavaScript files.
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]',
esModule: false
}
}
}
module.exports = {
entry: [
// load any web API polyfills
// path.resolve(appDirectory, 'polyfills-web.js'),
// your web-specific entry file
path.resolve(appDirectory, 'index.web.js')
],
output: {
filename: '[name].[contenthash].js',
publicPath: '/',
path: path.resolve(appDirectory, 'dist')
},
module: {
rules: [
babelLoaderConfiguration,
imageLoaderConfiguration,
{
test: /\.tsx?$/,
loader: 'ts-loader',
// exclude: /node_modules/,
options: {
configFile: 'tsconfig.web.json',
transpileOnly: true
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new CleanWebpackPlugin(),
new webpack.IgnorePlugin({
resourceRegExp: /react-native-screens/
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, './index.html')
}),
new CopyPlugin({
patterns: [
{
context: __dirname,
from: './images/**/*',
to: '[path][name][ext]',
force: true
},
{ from: path.join(__dirname, './main.css'), to: './main.css' },
{
from: path.join(__dirname, './.well-known/apple-app-site-association'),
to: './.well-known/'
}
]
}),
new webpack.HotModuleReplacementPlugin()
],
resolve: {
alias: {
'react-native$': 'react-native-web',
'react-native-maps$': 'react-native-web-maps'
},
extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js', '.json']
}
}
I tried implementing something that looks like showing in this documentation but it did not help.
https://docs.sentry.io/platforms/javascript/guides/react/sourcemaps/uploading/webpack/
You need to add #sentry/react-native to compile.
Update you webpack config like this:
...
const compileNodeModules = [
'#sentry/react-native'
]
const babelLoaderConfiguration = {
...
...compileNodeModules
}

Material Design - Getting Started - Error

I have followed the Material Design (Getting Started) Guide and in step 3 (add js) there is an error that I cannot find.
https://material.io/develop/web/getting-started#appendix-configuring-a-sass-importer-for-nested-node_modules
const autoprefixer = require('autoprefixer');
module.exports = {
entry: ['./app.scss', './app.js'],
output: {
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: 'bundle.css',
},
},
{loader: 'extract-loader'},
{loader: 'css-loader'},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
autoprefixer()
]
}
}
},
{
loader: 'sass-loader',
options: {
// Prefer Dart Sass
implementation: require('sass'),
// See https://github.com/webpack-contrib/sass-loader/issues/804
webpackImporter: false,
sassOptions: {
includePaths: ['./node_modules'],
},
},
}
],
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env'],
},
}
],
},
};
ERROR:
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.module.rules[1] has an unknown property 'query'. These properties are valid:
object { compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }
-> A rule description with conditions and effects for modules.
Error is pretty much telling you: The configuration.module.rules[1].query keyword is not valid. I believe it's options in webpack v5+. Try:
...
{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
}

How can I make FontAwesome work with vue-cli webpack-simple template?

I generate a default project with vue-cli:
vue init webpack-simple grid-prototype
I install FontAwesome through npm:
npm install --save fontawesome
After that, I include it into main.js with:
import 'font-awesome/css/font-awesome.css'
I execute the app with:
npm run dev
And I get this error:
Failed to compile.
./node_modules/font-awesome/fonts/fontawesome-webfont.ttf?v=4.7.0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/css-loader!./node_modules/font-awesome/css/font-awesome.css 7:684-735
# ./node_modules/font-awesome/css/font-awesome.css
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8082 webpack/hot/dev-server ./src/main.js
Here's my webpack.config.js (it's the default one created by the cli):
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/",
filename: "build.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ["vue-style-loader", "css-loader"]
},
{
test: /\.vue$/,
loader: "vue-loader",
options: {
loaders: {}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: "file-loader",
options: {
name: "[name].[ext]?[hash]"
}
}
]
},
resolve: {
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue", ".json"]
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: "#eval-source-map"
};
if (process.env.NODE_ENV === "production") {
module.exports.devtool = "#source-map";
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
]);
}
What am I doing wrong?
webpack-simple is suitable for quick prototyping and it doesn't have advanced rules.
Solution #1: Use webpack template instead of webpack-simple to avoid this and other issues in the future.
Solution #2: Use FontAwesome from CDN, for example:
https://www.bootstrapcdn.com/fontawesome/
I mean, just add the CDN css to your index.html
Solution #3: Add one more rule to your webpack config
module: {
rules: [
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
As it is in the webpack template:
https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js

Webpack with babel-loader not emitting valid es5

I have a webpack config that is based off https://github.com/vuejs-templates/webpack-simple/blob/master/template/webpack.config.js
It uses vue-loader and babel-loader. The issue is I cannot get it to generate ES5 code so that it will work in the most broad range of clients.
If I use the ES2015 preset, webpack.optimize.UglifyJsPlugin fails to minify the output because Uglify can only handle ES5 (not counting the harmony branch). The errors are similar to: Unexpected token: punc (() and occur in multiple files.
I can work around this by using babili-webpack-plugin which will minify the ES6 code but is very slow. However, when I deploy this code, I see errors being reported back saying Block-scoped declarations (let, const, function, class) not yet supported outside strict mode so I know they are older clients choking on ES6 code.
How can I get proper ES5 code output from babel-loader? I have tried multiple presets, with or without the transform-runtime plugin. Config below:
const webpack = require('webpack');
const globEntries = require('webpack-glob-entries');
const _ = require('lodash');
const path = require('path');
const BabiliPlugin = require("babili-webpack-plugin");
const env = process.env.NODE_ENV;
let entries;
if (env === 'production') {
entries = globEntries('./src/**/vue/*.js');
} else {
entries = _.mapValues(globEntries('./src/**/vue/*.js'), entry => [entry, 'webpack-hot-middleware/client?reload=true']);
}
module.exports = {
entry: entries,
output: {
path: '/', ///no real path is required, just pass "/"
publicPath: '/vue',
filename: '[name].js',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: 'vue-style-loader!css-loader!sass-loader',
sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
},
// other vue-loader options go here
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['es2015'],
plugins: ['transform-runtime'],
},
},
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
},
},
],
},
resolve: {
alias: {
vue$: 'vue/dist/vue.esm.js',
},
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Enable HMR
new webpack.NoEmitOnErrorsPlugin(),
],
performance: {
hints: false,
},
devtool: '#eval-source-map',
};
if (env === 'staging' || env === 'production') {
//module.exports.devtool = env === 'staging' ? '#source-map' : false;
module.exports.devtool = '#source-map';
module.exports.output.path = path.resolve(__dirname, './src/v1/parse/cloud/public/vue');
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `"${env}"`,
},
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false,
},
}),
// new BabiliPlugin(),
new webpack.LoaderOptionsPlugin({
minimize: true,
}),
]);
}
vue-loader will process your js with babel-loader (if it's detected), and uses .babelrc by default.
In your current setup you are not passing any options to Babel when it is used by vue-loader (meaning Babel uses no rules for your Vue files).
Either create .babelrc or specify the js loader by yourself for the .vue files to provide it with options:
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
js: 'babel?presets[]=es2015' // Pass parameters as options
}
}
}
The env preset for Babel has an uglify option that will fully compile to ES5. This preset is recommended practice to keep your environment up to date.
// .babelrc
{
"presets": [
[ "env", { "uglify": true } ],
"stage-1" // Or other presets not included with 'env' preset.
],
"plugins": ["transform-runtime"]
}
Instead of using preset es2015 only, you might add es2016 and es2017, as well as stage-4, stage-3, etc. to assure all your code is transformed, and not just the ES2015 parts.
Nothing wrong with answer here already, but here is a solution that does not require a .babelrc file. This answer works for a standalone webpack.config.js file. I got this answer from taking a look under the hood of the laravel-mix library.
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders:{
js: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
['env', {
'modules': false,
'targets': {
'browsers': ['> 2%'],
uglify: true
}
}]
],
plugins: [
'transform-object-rest-spread',
['transform-runtime', {
'polyfill': false,
'helpers': false
}]
]
}
},
}
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
I spent the better part of a day reading up all these useless blogs omit the core concept that babel-loader has to be attached to the vue-loader.

Syntax error when testing React component Jasmine and Webpack

I keep getting an error when trying to run a simple test using React, Karma, Jasmine and Webpack. The error is ' Uncaught SyntaxError: Unexpected token < ', I think my jsx isn't being processed to js, but I don't know why that is happening as I understand webpack should handle that using the babel loader. If anyone can provide advice I would be grateful
Here are my files
karma.conf.js
var webpack = require("webpack"),
path = require("path");
// Karma configuration
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"../test/!**!/!*.test.js"
],
preprocessors: {
"./test/!**!/!*.test.js": ["webpack"]
},
webpack: {
module: {
loaders: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{ test: /\.less$/, loader: "style!css!less" }
]
},
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
])
],
resolve: {
root: __dirname,
extensions: [
'',
'.json',
'.js',
'.jsx'
]
}
},
webpackMiddleware: {
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher")
],
reporters: ["dots"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false
});
};
my test file example.test.js
var Comp = require('../../../js/common/components/MyComp.jsx'),
React = require('react'),
TestUtils = React.addons.TestUtils;
describe("Component Test", function() {
it("renders an h1", function () {
var component = TestUtils.renderIntoDocument(
<Comp/> // syntax error here
);
var h2 = TestUtils.findRenderedDOMComponentWithTag(
component, 'h2'
);
expect(h1).toExist();
});
});
So the syntax error happens at < Comp... . Thanks!
Apologise it was an error in setting the correct path to the test file.
files: [
"../test/**/*.test.js"
],
preprocessors: {
"../test/**/*.test.js": ["webpack"]
},