Possible spread error on IE 11 (Webpack, VueJS)? - javascript

I'm getting this error on IE 11:
Here are my webpack and babel configuations:
webpack configuration
const path = require('path');
const webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');
const StylishWebpackPlugin = require('webpack-stylish');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const withLogRocket = process.argv.includes('--with-logrocket');
if (withLogRocket) {
/* eslint-disable no-console */
console.info('-> Building with LogRocket enabled.');
/* eslint-enable */
}
// Base webpack configuration for all environments.
module.exports = {
context: path.dirname(__dirname),
entry: {
app: './src/main.js',
},
target: 'web',
output: {
filename: '[name].[contenthash].js',
hashDigestLength: 8,
},
resolve: {
extensions: ['.ts', '.js', '.vue'],
alias: {
'#': path.resolve(__dirname, '../src'),
},
},
module: {
rules: [
{
test: /\.js/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
],
},
stats: 'errors-only',
plugins: [
new VueLoaderPlugin(),
new ForkTsCheckerWebpackPlugin({
tslint: true,
reportFiles: ['src/**/*.ts'],
}),
new StylishWebpackPlugin(),
new webpack.DefinePlugin({
USE_LOGROCKET: withLogRocket,
}),
],
};
babelrc file
{
"presets": ["env"],
"plugins": [
"transform-es2015-destructuring",
"transform-object-rest-spread"
]
}
I'm not really sure if this is due to the ...sources spread or among others. I'm pretty sure I have the babel-transform-object-rest-spread package but I still don't get why I have this error, I also used babel-preset-env. As you can see on the configuration I am running a pure JS (VueJS, typescript) app. I've read numerous posts about using polyfill and among others but it didn't help me make our app run on IE11.

You're using env preset but never defining what environment Babel is supposed to generate code for (so I assume IE 11 is not supported in that case).
Without any configuration options, babel-preset-env behaves exactly the same as babel-preset-latest (or babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together).
So just add the options object having the targets property set to something the like of
"browsers": [ "last 1 version", "ie >= 11" ]
like this:
{
"presets": ["env", {
"targets": {
"browsers": [ "last 1 version", "ie >= 11" ]
}
}],
"plugins": [
"transform-es2015-destructuring",
"transform-object-rest-spread"
]
}
I also highly recommend you switch to Babel 7 asap.

Related

Webpack not building because CssSyntaxError

I am trying to run a webpack-dev-server built, but it fails everytime with the following error:
ERROR in ./src/style.css (./node_modules/css-loader/dist/cjs.js!./node_modules/style-loader/dist/cjs.js!./node_modules/css-loader/dist/cjs.js!./src/style.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
CssSyntaxError
(1:1) Unknown word
> 1 | var api = require("!../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
| ^
2 | var content = require("!!../node_modules/css-loader/dist/cjs.js!./style.css");
3 |
My webpack.dev.js looks like this:
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
entry: './src/index.js',
mode: 'development',
devtool: 'inline-source-map',
optimization: {
usedExports: true,
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
],
},
});
The error appears on using this in my index.js:
import './style.css';
Many solutions suggest the order of the style-loader and the css-loader, but as far as I know it is in the correct order. What am I doing wrong?
I had the same error when trying to use the style-loader and the MiniCssExtractPlugin simultaneously. Your example uses webpack merge, so I assume that you also have a webpack.common.js somewhere with additional CSS rules?
In my case, what solved it was as following:
I have the following rules in my webpack.dev.config.js:
module: {
rules: [
{
test: /\.(sass|scss)$/,
use: [
"style-loader",
"css-loader",
"postcss-loader",
{
loader: "sass-loader",
options: {
// Prefer `dart-sass`
implementation: require("sass"),
},
},
],
},
],
},
And the following in my webpack.prod.config.js:
module: {
rules: [
{
test: /\.(sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
{
loader: "sass-loader",
options: {
// Prefer `dart-sass`
implementation: require("sass"),
},
},
],
},
],
},
You could also use the ternary operator to check if mode === 'production' and leave it in one file but I prefer to have two separate files to keep it more readable in case the webpack configs get too big.
I also tried to move the css-loader, postcss-loader and sass-loader to the same webpack.common.js file but for some reason it didn't work.
Not sure if that might be cause of your error but it fixed it in my use case so now I use the style loader for my dev environment and the plugin to compile for production.
This worked for webpack 5 and node 16

babel transpile to es5 doesnt work for node_modules

I am trying to run my current project in ie11, but it gives me an error saying SCRIPT1002: syntax error in foundation.js (its part of google's material design classes). The line in question is export default MDCFoundation. Now from what i have red the issue is that this is es6 code and ie11 only supports es5. So far so good. The problem now is I cant seem to figure out how to tell babel to transpile to es5. I am using webpack and babel, here is my webpack.config.js:
var path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var LiveReloadPlugin = require('webpack-livereload-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
entry:{
app: ['./src/app.js']
},
devtool: 'inline-source-map',
externals: /^(tables.)/i,
module: {
rules:
[
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
},
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader, // <---- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
}
}
],
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, // <--- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['./node_modules'],
},
}
],
},
{
test: /\.js$/,
include: /src/,
loader: 'babel-loader',
options: {
"presets": [
["env", {
"targets": {
"browsers": ["ie >= 11"]
}
}]
]
}
}
],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'style.css'}),
new LiveReloadPlugin({}),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery' })
],
resolve: {
extensions: ['.js']
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
},
output: {
publicPath: './dist',
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
}
};
As you can see I am already trying to tell babel to transpile for ie11, but it still gives me the same error.

Using babel plugin in webpack configuration file

In their website, webpack shows plugin usage like this
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
I want to use babel plugin transform-async-to-generator, so I added it in babelrc file but I dont know this is enough, should I add it also webpack file ? If so how
I can not be sure if writing plugin in webpack config file required because right now I am getting runtime error and not sure if it works writing only in babelrc file.
my current webpack config file
var path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'partner/index.js'),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'partner_bundle.js'
},
target: 'web',
module: {
rules: [
{
test: /\.js$/, // Check for all js files
loader: 'babel-loader',
query: {
presets: [
'babel-preset-env',
'babel-preset-stage-0'
].map(require.resolve)
},
exclude: /node_modules\/(?!other-module)/
}
]
},
stats: {
colors: true
},
devtool: 'source-map',
resolve: { symlinks: false }
}
babelrc file
{
"presets": [
"env",
"stage-2"
],
"plugins": [
"transform-async-to-generator",
"transform-async-generator-functions",
[
"transform-runtime",
{
"helpers": false,
"polyfill": false,
"regenerator": true
}
]
]
}
Here you can see in my webpack config how I include the babel plugins:
test: /(\.jsx|\.js)$/, // JSX and JS files should be present.
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'babel-loader',
options: {
// Babel must be required like this to be able to use npm-link to link to shared code, see:
// https://stackoverflow.com/questions/34574403/how-to-set-resolve-for-babel-loader-presets/
presets: [
[node_modules + '/#babel/preset-env', {
// Ref: 1) http://2ality.com/2017/02/babel-preset-env.html
// 2) http://caniuse.com/usage-table
// In case it supports the browserlist in package.json, remove this here, see:
// https://github.com/babel/babel-preset-env/issues/149
"targets": {"browsers": ["> 4%", "safari 10", "ie 11", "iOS 9"]},
"modules": false,
"useBuiltIns": 'entry',
// "debug": true
}],
[node_modules + '/#babel/preset-react'],
],
plugins: [
node_modules + '/#babel/plugin-proposal-class-properties',
node_modules + '/#babel/plugin-proposal-object-rest-spread'].map(require.resolve)
}
}]

How to setup webpack for supporting ES6 Modules in Node

I'm using Webpack for bundle client and server code, so my webpack.config.js looks like:
module.exports = [
{ /* client config */ },
{ /* server config */ },
];
I want to write ES6 (modules) in both and transpile code to ES5 using Babel.
For client, this can be done with babel-loader:
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [
'react',
[
'env',
{
targets: {
'browsers': 'last 2 versions',
},
},
],
],
},
}
Based on this, I wrote babel loader for server:
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: [
'react',
[
'env',
{
targets: {
'node': 'current',
},
},
],
],
},
}
Something tells me that babel-loader will never work for this purpose.
After ran webpack, bundles are right located but server entry point (server.js) aren't transpiled correctly:
SyntaxError: Unexpected token import
Generally when we want to transpile Node code, we would use babel-cli package and add a script in package.json:
"scripts": {
"build": "babel src -d dist"
}
and manually:
npm run build
My question is: How to setup ES6 transpiling with Babel for Node inside webpack.config.js?
+BONUS
webpack.config.js
const path = require('path');
const babelRcClient = {
presets: [
'react',
[
'env',
{
targets: {
'browsers': 'last 2 versions',
},
},
],
],
};
const babelRcServer = {
presets: [
'react',
[
'env',
{
targets: {
'node': 'current',
},
},
],
],
};
const babelLoaderClient = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: babelRcClient,
};
const babelLoaderServer = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: babelRcServer,
};
module.exports = [
{
context: __dirname,
entry: './shared/index.js',
output: {
path: path.resolve(__dirname, './static'),
filename: 'bundle.js',
},
module: {
loaders: [
babelLoaderClient,
],
},
plugins: [],
},
{
context: __dirname,
entry: './server/server.js',
target: 'node',
output: {
path: path.resolve(__dirname, './build'),
filename: 'server.js',
libraryTarget: 'commonjs',
},
externals: [ /^(?!\.|\/).+/i, ],
module: {
loaders: [
babelLoaderServer,
],
},
plugins: [],
},
]
By specifying
targets: {
'node': 'current',
}
you are telling babel to transpile your code to node version which you are using to transpile the code.
Are you using the same node version on production?
Try specifying numeric node version, e.g. 6.11.2 and then run transpilation.
Another thing you can do is tell babel to leave ES6 modules in ES6 way and don't replace it with commonjs approach (which is default) by setting:
targets: {
'node': ...,
},
modules: false
This thing worked for me. Try and check once.
{
test: /\.(js|jsx)$/,
include: [].concat(
path.resolve('./app') //path to your application
),
use: ['babel-loader']
}

Webpack 2 sourcemaps not generating

Webpack 2 source-map are not generating for javascript and css. It doesn't even show error. I used same syntax as the official documentation. I even added uglifyJs plugin sourcemap parameter to true. Can anybody please help me?
Below is my webpack config
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require('webpack');
const extractSass = new ExtractTextPlugin({
filename: "vendor-styles.css"
});
module.exports = {
entry: './js/app/index.js',
output: {
path: path.resolve(__dirname, "./js/dist/"),
filename: "[name].js"
},
devtool: "source-map",
plugins: [
extractSass,
new webpack.ProvidePlugin({
Promise: 'es6-promise-promise',
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
new webpack.optimize.UglifyJsPlugin({sourceMap: true})
],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: [
'env',
'react'
]
}
},
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
sourceMap: true,
importLoaders: true
}
}, {
loader: "sass-loader",
options: {
sourceMap: true
}
}],
// use style-loader in development
fallback: "style-loader"
})
},
{
test: /\.css$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
sourceMap: true,
importLoaders: true
}
}],
// use style-loader in development
fallback: "style-loader"
})
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: "url-loader?limit=10000&mimetype=application/font-woff&name=/css/fonts/[name].[ext]"
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: "url-loader?limit=10000&mimetype=application/font-woff&name=/css/fonts/[name].[ext]"
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: "url-loader?limit=10000&mimetype=application/octet-stream&name=/css/fonts/[name].[ext]"
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: "file-loader?name=/css/fonts/[name].[ext]"
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: "url-loader?limit=10000&mimetype=image/svg+xml&name=/css/fonts/[name].[ext]"
},
{
test: /\.(png|jpg|jpeg|gif)$/,
loader: 'url-loader'
},
]
}
}
I had the same problem but I finally got webpack to spit out sourcemaps for my .jsx files, by using the SourceMapDevToolPlugin. I straight copied it from the example in the docs; https://webpack.js.org/plugins/source-map-dev-tool-plugin/
Hope it helps :)
Add this line of code before entry devtool: 'cheap-module-eval-source-map', then in the debugger you should get exact line number of error.
I was having the same problem that #pritesh-panjiker was having.
What actually solved it for me was the simple addition of:
{sourceMap: true}
Into the the line of code:
new webpack.optimize.UglifyJsPlugin({sourceMap: true})
I also found these two documents very useful when I upgraded from Webpack 1 to Webpack 2:
https://moduscreate.com/blog/webpack-2-tree-shaking-configuration/
https://gist.github.com/sokra/27b24881210b56bbaff7

Categories

Resources