Webpack 4 + Babel 7 transform-runtime - Invalid configuration object - javascript

I'm currently using webpack 4 with babel 7 which was just released not long ago. Whenever I'm trying to run the latest webpack with babel on my project, I'm getting the following error currently with the plugin #babel/plugin-transform-runtime:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match
the API schema.
- configuration.plugins[0] should be one of these:
object { apply, … } | function
-> Plugin of type object or instanceof Function
Details:
* configuration.plugins[0] should be an object.
-> Plugin instance
* configuration.plugins[0] should be an instance of function
-> Function acting as plugin
- configuration.plugins[1] should be one of these:
object { apply, … } | function
-> Plugin of type object or instanceof Function
Details:
* configuration.plugins[1] misses the property 'apply'.
function
-> The run point of the plugin, required method.
* configuration.plugins[1] misses the property 'apply'.
function
-> The run point of the plugin, required method.
* configuration.plugins[1] should be an instance of function
-> Function acting as plugin
According to the documentation in https://babeljs.io/docs/en/babel-plugin-transform-runtime/, this should be working with the following example configuration for a .babelrc as an example (modifying this in my webpack.config.js to just turn corejs to true)
{
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": false,
"helpers": true,
"regenerator": true,
"useESModules": false
}]
]
}
webpack.config.js
var webpack = require('webpack');
var fiber = require('fibers');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: [
'#babel/polyfill',
'./src/jsx/app'
],
output: {
filename: 'bundle.js',
path: __dirname + '/dist'
},
mode: 'development',
devtool: 'source-map',
resolve: {
extensions: ['.js', '.jsx'],
},
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: 'main',
test: /\.css$/,
chunks: 'all',
enforce: true
}
}
}
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
{
'useBuiltIns': 'entry',
'modules': 'false'
},
'#babel/preset-env',
'#babel/preset-react'
],
plugins: [
require('#babel/plugin-syntax-dynamic-import'),
require('#babel/plugin-proposal-object-rest-spread')
]
}
}
},
{
test: /\.(scss|css)$/,
exclude: /node_modules/,
use: [
{
loader: this.mode === 'development' ? MiniCssExtractPlugin.loader : 'style-loader',
}, {
loader: 'css-loader',
options: {
sourceMap: true
}
}, {
loader: 'resolve-url-loader',
options: {
sourceMap: true,
keepQuery: true,
debug: this.mode === 'development'
}
}, {
loader: 'sass-loader',
options: {
outFile: 'src/style.css',
implementation: require('dart-sass'),
fiber: fiber,
sourceMap: true,
sourceComments: true,
sourceMapContents: true,
outputStyle: 'compressed',
includePaths: [
'node_modules/#fortawesome/fontawesome-pro/scss',
'node_modules/foundation-sites/scss',
'node_modules/motion-ui/src',
'node_modules/react-dates',
'node_modules/slick-carousel/slick',
'src/scss'
]
}
}
]
}
]
},
plugins: [
'#babel/plugin-transform-runtime', {
'corejs': true
},
new MiniCssExtractPlugin({
filename: this.mode === 'development' ? '[name].css' : '[name].[hash].css',
chunkFilename: this.mode === 'development' ? '[id].css' : '[id].[hash].css',
}),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './dist',
hot: true
}
};
dependencies from package.json
"devDependencies": {
"#babel/core": "7.0.0",
"#babel/plugin-proposal-object-rest-spread": "7.0.0",
"#babel/plugin-syntax-dynamic-import": "7.0.0",
"#babel/plugin-transform-runtime": "7.0.0",
"#babel/preset-env": "7.0.0",
"#babel/preset-react": "7.0.0",
"#babel/register": "7.0.0",
"babel-loader": "8.0.2",
"dart-sass": "1.13.1",
"electron": "2.0.8",
"electron-packager": "12.1.1",
"eslint": "5.4.0",
"eslint-plugin-react": "7.11.1",
"mini-css-extract-plugin": "0.4.2",
"react-hot-loader": "4.3.5",
"resolve-url-loader": "2.3.0",
"upath": "1.1.0",
"webpack": "4.17.2",
"webpack-cli": "3.1.0",
"webpack-dev-server": "3.1.7"
},
"dependencies": {
"#babel/polyfill": "7.0.0",
"#babel/runtime-corejs2": "7.0.0",
"#fortawesome/fontawesome-pro": "latest",
"chalk": "2.4.1",
"cheerio": "1.0.0-rc.2",
"colors": "1.3.2",
"fibers": "3.0.0",
"foundation-sites": "6.5.0-rc.2",
"jquery": "3.3.1",
"moment": "2.22.2",
"motion-ui": "2.0.3",
"react": "16.4.2",
"react-dates": "17.2.0",
"react-dom": "16.4.2",
"react-slick": "0.23.1",
"slick-carousel": "1.8.1",
"schema-utils": "1.0.0",
"what-input": "5.1.1"
}

Found the answer to those who are new to babel and webpack configuration such as me making this mistake:
webpack.config.js does NOT replace .babelrc and will need to be moved over for babel plugins such as the ones below in my .babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
["#babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}

Related

Webpack SyntaxError - Module build failed (from ./node_modules/babel-loader/lib/index.js)

I am setting up my ReactApp and just finished with it. So I wanted to make a settings class in a appsettings.ts file. So I can change some global variables easier.
But then all my issues started.
I know this problem is very common and there are tons of answers available but none of them have worked for me so far. I have searched through the internet to solve it but it still shows the same error.
This is the error I am getting:
ERROR in ../../../appsettings.ts
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: [APP_DIR]\appsettings.ts: Unexpected token (2:11)
1 | export class APPSETTINGS {
> 2 | public static EMAIL_SENDER: string = "name#example.com";
| ^
3 | public static EMAIL_RECIPIENT: string = "name#example.com";
4 | public static YEAR: number = (new Date()).getFullYear();
5 | }
at instantiate ([APP_DIR]\node_modules\#babel\parser\lib\index.js:67:32)
at constructor ([APP_DIR]\node_modules\#babel\parser\lib\index.js:364:12)
at Parser.raise ([APP_DIR]\node_modules\#babel\parser\lib\index.js:3364:19)
at Parser.unexpected ([APP_DIR]\node_modules\#babel\parser\lib\index.js:3397:16)
at Parser.parseClassMemberWithIsStatic ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13888:12)
at Parser.parseClassMember ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13773:10)
at [APP_DIR]\node_modules\#babel\parser\lib\index.js:13715:14
at Parser.withSmartMixTopicForbiddingContext ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12617:14)
at Parser.parseClassBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13694:10)
at Parser.parseClass ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13669:22)
at Parser.parseExportDeclaration ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14178:25)
at Parser.maybeParseExportDeclaration ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14135:31)
at Parser.parseExport ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14058:29)
at Parser.parseStatementContent ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13020:27)
at Parser.parseStatement ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12917:17)
at Parser.parseBlockOrModuleBlockBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13497:25)
at Parser.parseBlockBody ([APP_DIR]\node_modules\#babel\parser\lib\index.js:13489:10)
at Parser.parseProgram ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12832:10)
at Parser.parseTopLevel ([APP_DIR]\node_modules\#babel\parser\lib\index.js:12822:25)
at Parser.parse ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14674:10)
at parse ([APP_DIR]\node_modules\#babel\parser\lib\index.js:14716:38)
at parser ([APP_DIR]\node_modules\#babel\core\lib\parser\index.js:41:34)
at parser.next (<anonymous>)
at normalizeFile ([APP_DIR]\node_modules\#babel\core\lib\transformation\normalize-file.js:66:38)
at normalizeFile.next (<anonymous>)
at run ([APP_DIR]\node_modules\#babel\core\lib\transformation\index.js:21:50)
at run.next (<anonymous>)
at transform ([APP_DIR]\node_modules\#babel\core\lib\transform.js:22:41)
at transform.next (<anonymous>)
at step ([APP_DIR]\node_modules\gensync\index.js:261:32)
at [APP_DIR]\node_modules\gensync\index.js:273:13
at async.call.result.err.err ([APP_DIR]\node_modules\gensync\index.js:223:11)
# ./src/Page/Main/index.tsx 24:0-60 204:60-76 298:42-58
# ./src/App.tsx 5:0-31 14:38-42
# ./src/index.tsx 3:0-24 4:50-53
webpack 5.75.0 compiled with 1 error in 4752 ms
I got this error after I imported APPSETTINGS into my react app. If I delete the usage, then everything compiles fine, but with it, it just gives me this error
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv');
const CopyPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv.development === true;
const isEnvProduction = webpackEnv.production === true;
return {
target: 'web',
watch: isEnvDevelopment,
mode: isEnvProduction ? 'production' : 'development',
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, 'dist'),
publicPath: "/",
filename: isEnvProduction ? '[id].[hash].js' : '[name].bundle.js',
chunkFilename: isEnvProduction ? '[id].[hash].[chunkhash].chunk.js' : '[name].chunk.js',
},
devtool: isEnvDevelopment ? "source-map" : false,
devServer: {
compress: true,
port: 9000,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization",
https: true
},
historyApiFallback: true
},
resolve: {
mainFields: ['browser', 'main', 'module'],
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
// we use babel-loader to load our jsx and tsx files
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env"
]
}
},
},
{
test: /\.(css|scss)$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: {
localIdentName: isEnvProduction ? '[sha512:contenthash:base64]' : '[sha1:contenthash:hex:5]_____[local]'
},
importLoaders: 2,
sourceMap: isEnvDevelopment,
}
},
{
loader: "resolve-url-loader",
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
},
{
test: /\.(eot|otf|webp|ttf|woff|woff2|jpe?g|png|gif|svg)$/,
type: 'asset/resource'
},
{
test: /\.(pdf)(\?.*)?$/,
use: [
{
loader: "file-loader",
options: {
outputPath: "binary",
publicPath: "/binary"
}
},
],
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: isEnvProduction ? '[id].[hash].css' : '[name].bundle.css',
}),
new HtmlWebpackPlugin(),
new CopyPlugin({
patterns: [
{ from: 'src/static', to: '.' },
],
}),
new Dotenv({
path: isEnvProduction ? path.join(__dirname, "./.env.automated") : path.join(__dirname, "./.env")
}),
]
}
};
package.json
{
"name": "react-webapp",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"scripts": {
"dev": "webpack serve --env development",
"build": "webpack --env production"
},
"author": "",
"license": "ISC",
"dependencies": {
"#aws-amplify/api": "^4.0.18",
"#aws-amplify/api-graphql": "^2.2.7",
"#aws-amplify/auth": "^4.3.8",
"#aws-amplify/cache": "^4.0.20",
"#aws-amplify/core": "^4.3.0",
"aws-amplify": "^4.3.0",
"classnames": "^2.3.1",
"detect-browser": "^5.2.1",
"dotenv-webpack": "^7.0.3",
"graphql-tag": "^2.12.5",
"ibantools": "^4.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-loading": "^2.0.3",
"react-router-dom": "^5.3.0",
"regenerator-runtime": "^0.13.9"
},
"devDependencies": {
"#babel/core": "^7.20.2",
"#babel/plugin-proposal-class-properties": "^7.14.5",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.14.5",
"#babel/preset-typescript": "^7.15.0",
"#types/react": "^17.0.26",
"#types/react-dom": "^17.0.9",
"babel-loader": "^8.3.0",
"copy-webpack-plugin": "^9.0.1",
"css-loader": "^6.3.0",
"dotenv": "^10.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.3.0",
"node-sass": "^6.0.1",
"resolve-url-loader": "^4.0.0",
"sass-loader": "^12.1.0",
"typescript": "^4.4.3",
"typescript-plugin-css-modules": "^3.4.0",
"webpack": "^5.75.0",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.3.0"
}
}
You've installed #babel/preset-typescript but it's not added to the loader presets.
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-typescript"
"#babel/preset-env",
]
}
},
},
You may need to tweak the settings.

How to set up live reloading and assets compiling with Webpack in an MVC project?

So far I was able to set up Webpack to compile Sass and JavaScript. I compile a styles.scss and a index.js laying respectively in assets/scss/ and assets/js/ folders in my Drupal custom theme called amazon.
I generate a styles.css and a index.js in assets/dist/ folder. And those are included in my Twig templates with amazon.libraries.yml.
Is there a way to have live reloading as well? As for now, my assets get recompiled after each change but I have to reload the browser manually. I'm using Drupal v8.9.20 and Node.js v16.15.0.
assets/js/index.js:
import "../scss/styles.scss";
console.log("Hello World");
package.json:
{
"name": "amazon",
"scripts": {
"start": "webpack",
"build": "MODE=production webpack"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"autoprefixer": "^10.4.7",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"css-minimizer-webpack-plugin": "^3.0.2",
"mini-css-extract-plugin": "^2.1.0",
"postcss-loader": "^6.1.1",
"postcss-preset-env": "^7.6.0",
"sass": "^1.52.1",
"sass-loader": "^12.1.0",
"webpack": "^5.49.0",
"webpack-cli": "^4.9.1"
}
}
webpack.config.js:
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const target = process.env.MODE === "production" ? "browserslist" : "web";
const mode = process.env.MODE === "production" ? "production" : "development";
module.exports = {
entry: "./assets/js/index.js",
output: {
path: path.resolve(__dirname, "assets/dist"),
filename: "index.js",
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
url: false,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [["postcss-preset-env"]],
},
},
},
{
loader: "sass-loader",
options: {
implementation: require("sass"),
},
},
],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "styles.css",
}),
],
optimization: {
minimizer: ["...", new CssMinimizerPlugin()],
},
target: target,
devtool: mode == "production" ? false : "source-map",
mode: mode,
watch: mode !== "production",
};
.browserslistrc:
defaults
I could set up live reloading using BrowserSync. I'm proxying BrowserSync url, localhost:3000 with my Drupal development url, amazon.test.
The setup from the question is a good start, change package.json and webpack.config.js as below, run npm i, then npm start, and you are good to go.
package.json:
{
"name": "amazon",
"scripts": {
"start": "webpack",
"build": "MODE=production webpack"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"autoprefixer": "^10.4.7",
"babel-loader": "^8.2.2",
"browser-sync": "^2.27.10",
"browser-sync-webpack-plugin": "^2.3.0",
"css-loader": "^6.0.0",
"css-minimizer-webpack-plugin": "^3.0.2",
"mini-css-extract-plugin": "^2.1.0",
"postcss-loader": "^6.1.1",
"postcss-preset-env": "^7.6.0",
"sass": "^1.52.1",
"sass-loader": "^12.1.0",
"webpack": "^5.49.0",
"webpack-cli": "^4.9.1"
}
}
webpack.config.js:
const path = require("path");
const BrowserSyncPlugin = require("browser-sync-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const target = process.env.MODE === "production" ? "browserslist" : "web";
const mode = process.env.MODE === "production" ? "production" : "development";
module.exports = {
mode,
watch: mode !== "production",
entry: "./assets/js/index.js",
output: {
path: path.resolve(__dirname, "assets/dist"),
filename: "index.js",
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
url: false,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [["postcss-preset-env"]],
},
},
},
{
loader: "sass-loader",
options: {
implementation: require("sass"),
},
},
],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
],
},
plugins: [
new BrowserSyncPlugin(
// BrowserSync options
{
// browse to http://localhost:3000/ during development
host: "localhost",
port: 3000,
proxy: "amazon.test", // change to your own development url
files: [
{
match: ["**/*.php"],
},
{
match: ["templates/*.twig"],
},
{
match: ["**/*.js"],
},
{
match: ["**/*.scss"],
},
{
match: ["**/*.png"],
},
{
match: ["**/*.jpeg"],
},
{
match: ["**/*.jpg"],
},
{
match: ["**/*.svg"],
},
],
notify: false,
},
// plugin options
{
reload: true,
}
),
new MiniCssExtractPlugin({
filename: "styles.css",
}),
],
optimization: {
minimizer: ["...", new CssMinimizerPlugin()],
},
target: target,
devtool: mode == "production" ? false : "source-map",
};

SassError: Expected newline. #charset "UTF-8"; when building a Vue app with Sass as sass-loader on Webpack 4

I'm trying to build my Vue app on Node 13 and Webpack 4. For this I'm using this webpack.config.js
const { VueLoaderPlugin } = require("vue-loader");
const htmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const autoprefixer = require("autoprefixer");
const path = require("path");
const devMode = process.env.NODE_ENV !== 'production'
module.exports = {
mode: 'development',
entry: {
main: "./src/main.js",
},
output: {
filename: "[name].[contenthash:12].js",
path: path.resolve(__dirname, "dist"),
chunkFilename: "[name].[contenthash:12].js",
},
module: {
rules: [
{
test : /\.(jsx?)$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.vue$/,
loader: "vue-loader",
},
{
test: /\.(eot|ttf|woff|woff2|txt)(\?\S*)?$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
},
},
{
test: /\.(png|jpe?g|gif|webm|mp4|svg|ico)$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
outputPath: "assets/img",
esModule: false,
},
},
{
test: /\.(css)$/,
use: [
"vue-style-loader",
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: () => [autoprefixer()],
},
},
},
],
},
{
test: /\.(s(c|a)ss)$/,
use: [
"vue-style-loader",
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
sourceMap: true,
importLoaders: 2,
postcssOptions: {
plugins: () => [autoprefixer()],
},
},
},
"sass-loader",
{
loader: "sass-loader",
options: {
sourceMap: true,
implementation: require("sass"),
sassOptions: {
//fiber: require("fibers"),
prependData: `#import "app/javascript/manager/styles/main.scss"`,
//indentedSyntax: true
}
}
},
],
},
],
},
plugins: [
new VueLoaderPlugin(),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "[name].[contenthash:8].css",
chunkFilename: "[name].[contenthash:8].css",
}),
new htmlWebpackPlugin({
template: path.resolve(__dirname, "public", "index.html"),
favicon: path.resolve(__dirname, "public", "favicon.ico"),
}),
],
resolve: {
alias: {
vue$: "vue/dist/vue.runtime.esm.js",
},
extensions: ["*", ".js", ".jsx", ".css", ".scss", ".vue"],
modules: [
"node_modules",
]
},
optimization: {
moduleIds: "hashed",
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: -10,
chunks: "all",
},
},
},
},
devServer: {
historyApiFallback: true,
},
}
And this is my package.json
{
"name": "my-app-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#vue/compiler-sfc": "^3.1.4",
"axios": "^0.21.1",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"core-js": "^3.6.5",
"sass-loader": "10.1.1",
"style-loader": "^2.0.0",
"vue": "^2.6.11",
"vue-axios": "^3.2.4",
"vue-router": "^3.5.2",
"vuetify": "^2.5.6",
"webpack-war-plugin": "^1.0.0-beta.3"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"postcss": "^8.2.1",
"postcss-loader": "^4.2.0",
"sass": "1.32.13",
"sass-loader": "10.1.1",
"style-loader": "^2.0.0",
"vue-cli-plugin-vuetify": "~2.4.1",
"vue-loader": "^16.3.0",
"vue-template-compiler": "^2.6.14",
"vuetify": "^2.5.6",
"vuetify-loader": "^1.7.0",
"webpack": "^4.42.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
After struggling with the sass-loader I reduced the list of errors, but this one is significant and I haven't found a way to remove it:
ERROR in ./node_modules/vuetify/src/styles/main.sass (./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ref--5-3!./node_modules/sass-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--5-5!./node_modules/vuetify/src/styles/main.sass)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
╷
1 │ #charset "UTF-8";
│ ^
╵
No sass-node, just sass was used. Uncommenting indentedSyntax: true will simply drop another error saying that semicolons are not allowed. Upgrading versions will return other set of error. Fibers is out of scope (it just improves processing of certain async calls to my knowledge). Upgrading to Webpack5 adds a pletora of new problems as the json structure is quite different.
I'm totally stack at this point. There must be something else to work on the sass loader nut I'm not an expert on webpack so it's taking simply too long. Any help would be greatly appreciated at this point. I cannot believe none is having the same issue. I see many related answers but everyone seem to be doing fine just adding indentation. Thanks!

syntax error on arrow functions in IE11 when using webpack

I am using webpack to compile my existing javascript code for different browsers. You can find my current config below.
When I load the bundle that is generated in IE11 I get a SCRIPT1002: Syntax error on a line whith an arrow function.
Do any of you see something I can change to my config to make it work in IE11?
Package.json
"devDependencies": {
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/node": "^7.12.10",
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"glob": "^7.1.6",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"babel-loader": "^8.2.2"
}
webpack.config.js
const path = require('path');
const glob = require('glob');
require('#babel/register');
//webpack config
const config = [
{
entry: glob.sync('../../source/images/src/js/global.js'),
mode: 'development',
output: {
path: path.resolve(__dirname, './../../source/images/build/js/'),
filename: 'client.bundle.js'
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
},
{
entry: glob.sync('../../source/images/src/js/global.js'),
devtool: 'none',
mode: 'production',
output: {
path: path.resolve( __dirname, './../../source/images/build/js/'),
filename: 'client.bundle.min.js'
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
use: ['babel-loader']
}]
}
}
]
module.exports = config;
.babelrc
{
"presets": [
["#babel/preset-env", {
"debug": true,
"useBuiltIns": "usage",
"corejs": "7.7.0"
}]
]
}
.browserslistrc
not ie <= 9
> 0.25%

Syntax Error on dynamic import() using webpack and babel

I'm attempting to use a dynamic import to plug our server-generated config.js file into our production build of our app.
I attempt to use it in this way:
import('./config').then(function(config){
//create a global config variable
config = config;
})
(for now)
When I run webpack, I get the following error
Module build failed: SyntaxError: Unexpected token, expected { (1:6)
Research has led me to believe that this has something to do with babel-loader perhaps not playing nice with dynamic import, but I thought that had already been "solved" with a newer version.
Solutions seem to potentially have been to install Syntax Dynamic Import or maybe babel-plugin-dynamic-import-node, but it's not clear to me which one or why.
Relevant bits of my package.json:
{
"name": "app",
"version": "0.0.1",
"private": true,
"scripts": {
"build": "node config/webpack/build.js",
},
"dependencies": {
"amdi18n-loader": "^0.6.2",
"async": "^2.6.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.2.2",
"babel-loader": "^7.1.4",
"babel-plugin-istanbul": "^4.1.6",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-2": "^6.24.1",
"babel-register": "^6.26.0",
"chalk": "^2.3.0",
"css-loader": "^0.28.10",
"file-loader": "^1.1.6",
"html-webpack-plugin": "^3.2.0",
"less": "^3.0.1",
"less-loader": "^4.0.6",
"promise-polyfill": "^7.1.0",
"raw-loader": "^0.5.1",
"style-loader": "^0.20.2",
"webpack": "^4.5.0"
},
"devDependencies": {
"autoprefixer": "^7.2.3",
"chromedriver": "^2.34.0",
"copy-webpack-plugin": "^4.3.0",
"cross-env": "^5.1.1",
"cross-spawn": "^5.1.0",
"eslint": "^4.13.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-html": "^4.0.1",
"friendly-errors-webpack-plugin": "^1.6.1",
"inject-loader": "^3.0.1",
"madge": "^2.0.0",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.9",
"rimraf": "^2.6.2",
"semver": "^5.4.1",
"shelljs": "^0.7.8",
"source-map-support": "*",
"uglifyjs-webpack-plugin": "^1.1.4",
"url-loader": "^0.6.2",
"uuid": "^3.1.0",
"webpack-bundle-analyzer": "^2.9.1",
"webpack-cli": "^2.0.14",
"webpack-dev-server": "^3.1.3",
"webpack-merge": "^4.1.1"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
}
}
We split our webpack.conf.js into webpack.base.conf
'use strict';
const path = require('path');
const utils = require('./utils');
const config = require('../');
function resolve(dir) {
return path.join(__dirname, '../..', dir);
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
});
module.exports = {
context: path.resolve(__dirname, '../../'),
entry: {
app: './public/js/ide.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
resolve: {
extensions: ['.js', '.json', '.less'],
alias: {
'#': resolve('public/js'),
},
modules: ['less', 'node_modules']
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('public/js'), resolve('test')],
exclude: [
path.resolve(__dirname, "public/js/config.js")
],
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
},
{
test: /\.hbs$/,
use: ['raw-loader']
}
]
},
node: {
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
};
...and webpack.prod.conf.js
const webpackConfig = merge(baseWebpackConfig, {
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'public/html/ide.html'
: config.build.index,
template: 'public/html/ide.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../../public/fonts'),
to: config.build.assetsFonts,
},
{
from: path.resolve(__dirname, '../../public/img'),
to: config.build.assetsImg,
}
])
]
});
In 1, a user indicated that babel-loader should "just work" with dynamic imports now, so I'm not sure what I'm missing. Something out of date? Something weird in my config?
There are a couple of things you need to do.
First, like some people in the comments mentioned, you need to use a different variable name for your config. Also, if you use import this way, the object you get is a ES6 exported object, so your data will be in default
import('./config').then(function(localConfig){
//create a global config variable
config = localConfig.default;
})
Next, the error you are getting is the result of babel not using the correct preset. You need to be at least on stage-2 for this to work.
{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: ['es2015','stage-2']
}
include: [resolve('public/js'), resolve('test')],
exclude: [
path.resolve(__dirname, "public/js/config.js")
],
},
This will solve your error, but is still not what you want. All that is happening now is that webpack will split your config file into its own chunk, making a new http request on runtime to get this file. But it will not use the config file that is on the server, but the generated chunk from the build.
To load the actual config that you have on the server on runtime, you need to make a normal http request in your app.
Here is a good stackoverflow answer about this.
https://stackoverflow.com/a/36725115/9083959

Categories

Resources