Syntax Error on dynamic import() using webpack and babel - javascript

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

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.

Migrating from Webpack v4 to v5. Styling not picked up

I've migrated Webpack to v5 in my React project and none of my .scss files are picked up when I run it
I've followed this guide on migrating webpack https://webpack.js.org/migrate/5/ updated all plugins and loaders (all of them are MAJOR updates) that I use in development mode, updated configuration file to accommodate new versions but none of the styles are applied
My package.json:
"devDependencies": {
...
"clean-webpack-plugin": "^4.0.0",
"compression-webpack-plugin": "^10.0.0",
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.7.1",
...
"file-loader": "^6.2.0",
"fork-ts-checker-webpack-plugin": "^6.2.6",
"html-webpack-plugin": "^5.5.0",
...
"mini-css-extract-plugin": "^2.6.1",
...
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"react-hot-loader": "^4.13.0",
"sass-loader": "^13.1.0",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.6",
"ts-loader": "^9.4.1",
"webpack": "^5.74.0",
"webpack-bundle-analyzer": "^4.6.1",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
"sideEffects": [
"*.css",
"*.scss"
]
}
My webpack.config.json:
module.exports = {
mode: 'development',
entry: './src/index.tsx',
output: {
publicPath: '/',
path: outPath,
filename: 'bundle.js',
globalObject: 'this'
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: [
/(node_modules)/,
/\.test.tsx?$/,
/\.spec.tsx?$/
],
use: [
{loader: 'react-hot-loader/webpack'},
{
loader: 'ts-loader',
options: {
transpileOnly: true,
allowTsInNodeModules: false,
onlyCompileBundledFiles: true
}
}
]
},
{
test: /\.(css|scss)$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]',
},
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
}
]
}
]
}
};
This is how I import styles in my modules:
const styles = require('./index.scss')
<div className={styles['some-class']}>
When I was on previous webpack version everything worked fine, but as soon as I upgraded webpack and all the webpack related packages, styling is no longer applied.
Any help is highly appreciated
Since you're using require and not import, you have to specify default:
const styles = require('./index.scss').default;

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!

Webpack Hot Reload very slow

I'm quite new to Webpack and when I initially set it up with my project it was working great but it seems to have got much slower as my project has progressed (maybe because more and more packages get included?). It's now taking over 1 second according to the console output:
This does not seem accurate though because in reality it's taking between 5 and 10 seconds and usually I just get bored of waiting and hit F5 to reload the page because it'll just be quicker. I'd like to get back to letting HMR do it's thing but I need to figure out why it's so slow and fix before I can do that.
Here is my webpack.config.js:
/// <binding />
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const dirName = 'wwwroot/dist';
const devMode = process.env.NODE_ENV !== "production";
console.log('path:' + path.resolve(__dirname, 'wwwroot/images'));
module.exports = {
mode: devMode ? 'development' : 'production',
devtool: "source-map",
entry: {
app: './wwwroot/js/app.ts',
addadv: './wwwroot/js/pages/adventures/addadventure.ts'
},
output: {
path: path.resolve(__dirname, dirName),
filename: '[name].bundle.js',
publicPath: '/dist/'
},
optimization: {
splitChunks: {
chunks: 'initial'
}
},
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader?$!expose-loader?jQuery'
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node-modules/
},
{
test: /\.s[c|a]ss$/,
use: [
'css-hot-loader',
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
ctx: {
env: devMode ? 'development' : 'production'
}
}
}
},
'resolve-url-loader',
'sass-loader'
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
},
{
test: /\.(png|svg|jpg|gif)$/,
include: [
path.resolve(__dirname, 'wwwroot/images')
],
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images',
publicPath: 'images'
}
}
]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new CleanWebpackPlugin(dirName, {}),
new MiniCssExtractPlugin({
filename: "bundle.css",
chunkFilename: "bundle.css"
}),
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
statsOptions: { source: false }
})
]
};
and my package.json
{
"name": "tap.extranet",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch-dev": "webpack --watch",
"build-dev": "webpack",
"build-prod": "cross-env NODE_ENV=production webpack",
"analyse-bundles": "webpack-bundle-analyzer --port 4200 wwwroot/dist/stats.json"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.7.2",
"#types/jquery": "^3.3.29",
"#types/jqueryui": "1.12.7",
"#types/jquery.validation": "1.16.6",
"#types/jquery-validation-unobtrusive": "3.2.32",
"#types/webpack-env": "^1.13.7",
"#types/knockout": "^3.4.64",
"aspnet-webpack": "^3.0.0",
"autoprefixer": "^9.4.7",
"clean-webpack-plugin": "^1.0.1",
"cross-env": "^5.2.0",
"css-hot-loader": "^1.4.3",
"css-loader": "^2.1.0",
"cssnano": "^4.1.8",
"expose-loader": "^0.7.5",
"file-loader": "^3.0.1",
"font-awesome-loader": "^1.0.2",
"jquery": "^3.3.1",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.11.0",
"popper.js": "^1.14.7",
"postcss-loader": "^3.0.0",
"precss": "^4.0.0",
"resolve-url-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"ts-loader": "^5.3.3",
"typescript": "^3.3.3",
"url-loader": "^1.1.2",
"webpack": "^4.29.3",
"webpack-bundle-analyzer": "^3.0.4",
"webpack-cli": "^3.2.3",
"webpack-dev-middleware": "^3.5.2",
"webpack-hot-middleware": "^2.24.3",
"knockout": "3.5.0",
"knockout-sortable": "1.1.0",
"jquery-ui": "1.12.1"
},
"-vs-binding": {
"BeforeBuild": [
"build-dev"
],
"ProjectOpened": [
"watch-dev"
]
},
"dependencies": {
"bootstrap": "^4.3.0",
"font-awesome": "^4.7.0"
}
}
and finally, here is a screenshot of my bundles:
I've tried adding cache: true to the webpack config but that didn't make any difference.

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

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
}]
]
}

Categories

Resources