Eslint and Babel parser throwing errors in React - reactjs

Having some strange behaviour when trying to configure ESlint(global install) and babel:
Editor(VSCode) showing error on top most import:
Resolve error: TypeError: Cannot read properties of undefined (reading 'ENV')
at module.exports (.....\client\webpack.config.js:29:44)
at Object.exports.resolve (.....\client\node_modules\eslint-import-resolver-webpack\index.js:107:21)
while running npm run lint on the whole project throws:
.......\client\webpack.config.js
0:0 error Parsing error: No Babel config file detected for .......\client\webpack.config.js. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files
for every file it's trying to parse.
eslintrc.json
{
"globals": {
"graphql": true,
"theme": true,
"classes": true
},
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
"plugin:import/recommended"
],
"parser": "#babel/eslint-parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true,
"globalReturn": false
},
"ecmaVersion": "latest",
"sourceType": "module",
"babelOptions": {
"root": "./client/"
}
},
"plugins": [
"react",
"unused-imports",
"#babel",
"react-hooks",
"jsx-a11y",
"import"
],
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
"react/jsx-pascal-case": [
2,
{
"allowAllCaps": true
}
],
"jsx-quotes": [
"error",
"prefer-single"
],
"react/jsx-closing-bracket-location": [
1,
"tag-aligned"
],
"react/jsx-closing-tag-location": 1,
"no-multi-spaces": [
"error",
{
"ignoreEOLComments": true
}
],
"react/jsx-tag-spacing": 2,
"react/jsx-boolean-value": [
2,
"never"
],
"react/self-closing-comp": [
"error",
{
"component": true,
"html": true
}
],
"react/prop-types": "off",
"import/no-unresolved": [
"error",
{
"caseSensitive": false
}
],
"no-unused-vars": ["error", { "vars": "local", "args": "after-used" }], // or "#typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-imports": "off",
"unused-imports/no-unused-vars": [
"warn",
{
"vars": "all",
"varsIgnorePattern": "^_",
"args": "after-used",
"argsIgnorePattern": "^_"
}
],
"react/no-unknown-property": [
"error",
{
"ignore": [
"css"
]
}
],
"import/order": ["error", {
"newlines-between": "always",
"groups": ["builtin", "external", "internal", ["sibling", "parent"], "index"],
"alphabetize": {
"order": "asc"
}
}],
"import/namespace": "error",
"import/no-duplicates": "error",
"import/no-self-import": "error",
"react-hooks/exhaustive-deps": "error",
"object-curly-spacing": ["error", "always"],
"template-curly-spacing": ["error", "always"],
"react/jsx-curly-spacing": ["error", {"when": "always"}]
},
"settings": {
"react": {
"createClass": "createReactClass", // Regex for Component Factory to use,
// default to "createReactClass"
"pragma": "React", // Pragma to use, default to "React"
"fragment": "Fragment", // Fragment to use (may be a property of <pragma>), default to "Fragment"
"version": "detect", // React version. "detect" automatically picks the version you have installed.
// You can also use `16.0`, `16.3`, etc, if you want to override the detected value.
// default to latest and warns if missing
// It will default to "detect" in the future
"flowVersion": "0.53" // Flow version
},
"propWrapperFunctions": [
// The names of any function used to wrap propTypes, e.g. `forbidExtraProps`. If this isn't set, any propTypes wrapped in a function will be skipped.
"forbidExtraProps",
{
"property": "freeze",
"object": "Object"
},
{
"property": "myFavoriteWrapper"
},
// for rules that check exact prop wrappers
{
"property": "forbidExtraProps",
"exact": true
}
],
"componentWrapperFunctions": [
// The name of any function used to wrap components, e.g. Mobx `observer` function. If this isn't set, components wrapped by these functions will be skipped.
"observer", // `property`
{
"property": "styled"
}, // `object` is optional
{
"property": "observer",
"object": "Mobx"
},
{
"property": "observer",
"object": "<pragma>"
} // sets `object` to whatever value `settings.react.pragma` is set to
],
"formComponents": [
// Components used as alternatives to <form> for forms, eg. <Form endpoint={ url } />
"CustomForm",
{
"name": "Form",
"formAttribute": "endpoint"
}
],
"linkComponents": [
// Components used as alternatives to <a> for linking, eg. <Link to={ url } />
"Hyperlink",
{
"name": "Link",
"linkAttribute": "to"
}
],
"import/resolver": {
"node": {
"paths": [
"client/src",
"src"
],
"extensions": [
".js",
".jsx",
".ts",
".tsx"
]
},
"webpack": {
"config": "webpack.config.js"
}
}
}
}
babel.config.json
{
"presets": [
"#babel/env",
"#babel/react",
"#emotion/babel-preset-css-prop"
],
"plugins": [
"syntax-dynamic-import",
"react-hot-loader/babel",
"#babel/plugin-transform-react-jsx-source"
]
}
webpack.config.js
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const dotenv = require('dotenv')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const port = 3000
const host = '0.0.0.0'
module.exports = (env) => {
const currentPath = path.join(__dirname)
const envPath = currentPath + `/${ env.ENV }.env`
const fileEnv = dotenv.config({ path: envPath }).parsed
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${ next }`] = JSON.stringify(fileEnv[next])
return prev
}, {})
const isProd = (env.ENV === 'prod')
return {
mode: isProd ? 'production': 'development',
entry: [
path.resolve('src', 'index.js')
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: isProd ? '[name].[chunkhash].js' : '[name].[hash:8].js',
chunkFilename: isProd ? '[id].[chunkhash].js' : '[id].[hash:8].js',
sourceMapFilename: isProd ? '[name].[chunkhash].map' : '[name].[hash:8].map',
},
module: {
rules: [
{
test: /\.(jpe?g|png|svg)$/i,
type: 'asset',
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test:/\.css$/,
//include: path.resolve(__dirname, 'node_modules'),
use: ['style-loader', 'css-loader']
},
{
test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
exclude: /node_modules/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'content/fonts/'
}
}]
}
]
},
resolve: {
extensions: ['.js', '.jsx', 'json'],
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
services: path.join(__dirname, 'src/services/'),
utils: path.join(__dirname, 'src/utils/'),
Redux: path.join(__dirname, 'src/redux/'),
scss: path.join(__dirname, 'src/scss/'),
hooks: path.join(__dirname, 'src/hooks/'),
config: path.join(__dirname, 'src/config/'),
components: path.join(__dirname, 'src/components/'),
modules: path.join(__dirname, 'src/modules/'),
locales: path.join(__dirname, 'src/locales/'),
routes: path.join(__dirname, 'src/routes/')
},
preferRelative: true,
roots: [path.resolve(__dirname), 'content']
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from:'src/content/images',
to: 'content/images',
globOptions: {
ignore: ['**/index.html']
}
}
],
}),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body',
//favicon: './content/favicon.ico'
}),
new webpack.DefinePlugin(envKeys)
],
devtool: 'eval-cheap-source-map',
devServer: {
hot: true,
host: host,
port: port,
historyApiFallback: true,
headers: { 'Access-Control-Allow-Origin': '*' },
static: {
directory: path.resolve(__dirname, 'content'),
publicPath: '/content'
}
}
}
}
Edit: I fixed the VSCode complaining with adding this to eslintrc's import-resolver rule:
"webpack": {
"config": "webpack.config.js",
"env":{
"ENV": "dev",
"production": false
}
}

Related

Aliases (import) doesn't work with Storybook

When I run storybook, my aliases are ignored.
It work fine when I run my project.
I tried to define all my aliases in the main.js file, but i doesn't work better. Do you know why ?
I've already visit this page and i think i do the right config (?) https://storybook.js.org/docs/react/builders/webpack
Bellow my code.
Here my dependencies (package.json) :
"#storybook/addon-a11y": "^6.5.16",
"#storybook/addon-postcss": "^2.0.0",
"storybook-addon-sass-postcss": "^0.1.3",
"storybook-react-i18next": "^1.1.2",
"#storybook/addon-actions": "^6.5.16",
"#storybook/addon-essentials": "^6.5.16",
"#storybook/addon-interactions": "^6.5.16",
"#storybook/addon-links": "^6.5.16",
"#storybook/builder-vite": "^0.4.0",
"#storybook/react": "^6.5.16",
"#storybook/testing-library": "^0.0.13"
Here my storybook config file (main.js)
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const path = require('path')
module.exports = {
stories: [
"../packages/frontend/src/**/*.stories.mdx",
"../packages/frontend/src/**/*.stories.#(js|jsx|ts|tsx)"
],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
"storybook-react-i18next",
"#storybook/addon-a11y",
"#storybook/addon-postcss",
"storybook-addon-sass-postcss"
],
framework: "#storybook/react",
core: {
builder: "#storybook/builder-vite"
},
features: {
storyStoreV7: true
},
webpackFinal: async (config) => {
config.resolve.plugins = [
...(config.resolve.plugins || []),
new TsconfigPathsPlugin({
extensions: config.resolve.extensions,
}),
],
// FIXME - why alias not working ???
config.resolve.alias = {
...config.resolve.alias,
'#public': path.resolve(__dirname, '/public'),
'#internals/components': path.resolve(__dirname, '/src/components'),
'#internals/features': path.resolve(__dirname, '/src/features'),
'#internals/hooks': path.resolve(__dirname, '/src/hooks'),
'#internals/models': path.resolve(__dirname, '/src/models'),
'#internals/utils': path.resolve(__dirname, '/src/utils'),
'#internals/types': path.resolve(__dirname, '/src/types'),
'#internals/styles': path.resolve(__dirname, '/src/styles'),
'#internals/assets': path.resolve(__dirname, '/src/assets'),
'#internals/store': path.resolve(__dirname, '/src/store'),
'#internals/config': path.resolve(__dirname, '/src/config'),
'#internals/services': path.resolve(__dirname, '/src/services'),
}
// resolve baseUrl path set in tsconfig
config.resolve.modules = [
...(config.resolve.modules || []),
path.resolve(__dirname, "../packages/frontend/src/"),
];
config.module.rules.push({
test: /\.scss$/,
sideEffects: true, // scss is considered a side effect of sass
use: [
"style-loader",
"css-loader",
"sass-loader",
],
include: path.resolve(__dirname, "../packages/frontend/src/"),
})
return config
},
typescript: {
check: false,
checkOptions: {},
reactDocgen: 'none',
// reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true,
propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
},
},
}
My Typescript config (tsconfig.json)
{
"compilerOptions": {
"baseUrl": ".",
"target": "ES6",
"jsx": "react-jsx",
"allowJs": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"declaration": true,
"types": [
"vite/client",
"vitest"
],
"moduleResolution": "node",
"paths": {
"#internals/components/*": [
"./src/components/*"
],
"#internals/features/*": [
"./src/features/*"
],
"#internals/hooks/*": [
"./src/hooks/*"
],
"#internals/models/*": [
"./src/models/*"
],
"#internals/utils/*": [
"./src/utils/*"
],
"#internals/types/*": [
"./src/types/*"
],
"#internals/styles/*": [
"./src/styles/*"
],
"#internals/assets/*": [
"./src/assets/*"
],
"#internals/store/*": [
"./src/store/*"
],
"#internals/services/*": [
"./src/services/*"
],
"#internals/config/*": [
"./src/config/*"
],
"#public/*": [
"./public/*"
],
},
},
"files": [],
"include": ["src/**/*.ts", "src/**/*.tsx", "vitest.config.ts"],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"extends": "../../tsconfig.base.json"
}

ESLint issue when using babel module-resolver and typescript

TS is not inferring the type when using resolved imports, but it does when using relative imports. Any help would be appreciated.
useTheme has
"Unsafe call of an 'any' typed value."
This error does not show up if i use a relative import instead of '#theme/Theme'
My project structure is:
Here are my config files:
tsconfig.json
{
"extends": "../../tsconfig.json", // standard tsconfig params
"compilerOptions": {
"jsx": "react-native" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
"baseUrl": "." /* Base directory to resolve non-absolute module names. */,
"paths": {
"#components/*": ["./src/common/components/*"],
"#theme/*": ["./src/lib/theme/*"],
"#hooks/*": ["./src/common/hooks/*"],
"#features/*": ["./src/features/*"]
},
"typeRoots": [
"./typings",
"../../node_modules/#types"
] /* List of folders to include type definitions from. */
},
"include": ["../"],
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
'#babel/preset-typescript',
],
plugins: [
['#babel/plugin-proposal-optional-chaining'],
['#babel/plugin-proposal-nullish-coalescing-operator'],
['#babel/plugin-proposal-decorators', { legacy: true }],
[
'module:react-native-dotenv',
{
moduleName: '#env',
path: '.env',
},
],
[
'module-resolver',
{
alias: {
'#components': './src/common/components',
'#theme': ['./src/lib/theme'],
'#hooks': ['./src/common/hooks'],
'#features': ['./src/features'],
},
extensions: ['.js', '.jsx', '.ts', '.tsx'],
root: '.',
},
],
'react-native-reanimated/plugin',
],
};
.eslintrc
{
"root": true,
"extends": [
"airbnb-typescript", // React "airbnb-typescript/base" for just js. "airbnb","airbnb/base" for no TypeScript
"airbnb/hooks", // React
"plugin:#typescript-eslint/eslint-recommended",
"plugin:#typescript-eslint/recommended",
"plugin:#typescript-eslint/recommended-requiring-type-checking",
"#react-native-community" // React Native only
],
"parser": "#typescript-eslint/parser", // TypeScript only
"parserOptions": {
"project": "./tsconfig.json", // TypeScript only
"ecmaFeatures": { "jsx": true }
},
"settings": {
"import/resolver": {
"babel-module": {}
}
},
"plugins": ["import", "#typescript-eslint"],
"ignorePatterns": ["*.config.js"],
"overrides": [
{
/** Testing Files Extensions */
"files": ["*.{spec,test}.{js,ts,tsx}", "e2e/*.{js,ts,tsx}"],
"plugins": ["jest"],
"env": { "jest/globals": true },
"rules": {
"import/no-extraneous-dependencies": 0 // Allow dev-dependency imports
}
}
],
"rules": {
"no-unused-vars": [
"error",
{
"args": "none",
"caughtErrors": "none",
"ignoreRestSiblings": true,
"vars": "all"
}
],
// resolve "import/extensions"
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never",
"tsx": "never"
}
],
"curly": ["error", "multi-line"],
"no-void": ["error"], // Allow void as statement in order to ignore promise returns
"prettier/prettier": 0, // Disable Prettier
"import/no-cycle": 0, // Slows down all linting
"react/jsx-props-no-spreading": 0, // Enable Prop Spreading
"#typescript-eslint/no-empty-interface": 0, // Allow boilerplate empty interfaces for defining component props explicitly
"#typescript-eslint/no-unsafe-assignment": 0,
"#typescript-eslint/naming-convention": [
2,
{
"leadingUnderscore": "allow",
"format": ["camelCase", "PascalCase", "UPPER_CASE", "snake_case"],
"selector": "variable"
}
],
"#typescript-eslint/no-explicit-any": 0, // disabled to avoid using any type
"#typescript-eslint/no-use-before-define": "off",
"#typescript-eslint/restrict-template-expressions": 0,
"#typescript-eslint/no-floating-promises": [2, { "ignoreIIFE": true }], // Fixes issue where async await syntax wasn't being recognised.
"#typescript-eslint/explicit-function-return-type": [
0,
{ "allowExpressions": false }
],
"#typescript-eslint/no-unused-vars": [2, { "varsIgnorePattern": "^_" }],
// Fixes false-positives for enums in typescript https://github.com/typescript-eslint/typescript-eslint/issues/2484#issuecomment-687257773
"no-shadow": "off",
"#typescript-eslint/no-shadow": ["error"],
"max-len": [
"warn",
{
"code": 120,
"tabWidth": 2,
"ignoreComments": true,
"ignoreStrings": true,
"ignoreRegExpLiterals": true,
"ignoreTemplateLiterals": true
}
]
}
}
if you work in vscode, try use "TypeScript: Select TypeScript version" to select you workspace version

React 17 and webpack 5 not working in IE11

I have looked into everything I could about the migration to react 17 and webpack 5. This for an application that is also running on IE11. And after all the changes (as you will see in the code) , according to evrything I read, it still doesnt work. I get the same error . When I look at the bundle and open it, there is a const there, which belongs to es6. It means that there was not translation, despite all the babel change I made.
If someone has an idea what could be done it would great!
Here is my webpack fike:
const webpack = require('webpack');
const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const autoprefixer = require('autoprefixer');
const Dotenv = require('dotenv-webpack')
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
const nodeEnv = process.env.NODE_ENV || "development"
const simulateProd = process.env.SIMULATE_PROD
const isProdEnv = nodeEnv === 'production'
const isNotDevEnv = nodeEnv !== "development"
const buildPath =
const sourcePath =
const imagesPath =
const iconsPath =
const soundsPath = ;
// Common plugins
const plugins = [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
new MiniCssExtractPlugin(),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer(),
],
context: sourcePath,
},
}),
new CopyWebpackPlugin(
{
patterns: [
{from: iconsPath, to: 'icons'},
{from: imagesPath, to: 'images'}
]
}
),
new Dotenv({
systemvars: true
}),
new HtmlWebpackPlugin({
template: path.join(sourcePath, 'index.html'),
path: buildPath,
filename: 'index.html',
}),
]
// Common rules
const rules = [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
plugins: ['react-hot-loader/babel'],
presets: ["#babel/preset-env"] //Preset used for env setup
}
// use: [
// 'babel-loader',
// ],
},
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
{
// creates style nodes from JS strings
loader: "style-loader",
// options: {sourceMap: true}
},
// Translates CSS into CommonJS
{
loader: 'css-loader',
options: {
importLoaders: 1,
url: false,
modules: {localIdentName: "[path]___[name]__[local]___[hash:base64:5]"}
}
},
{
loader:"resolve-url-loader"
},
{
// compiles Sass to CSS
loader: "sass-loader",
options: {
sourceMap: true
}
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "style-loader", 'css-loader'],
},
{
test: /\.(ico|jpe?g|png|gif|svg|mp3|html)$/,
include: [imagesPath, soundsPath],
type: 'asset/resource',
// use: 'file-loader',
// generator: {
// filename: '[path][name].[ext]'
// },
},
{
test: /\.md$/,
use: 'raw-loader'
}
]
if (isProdEnv) {
// Production plugins
plugins.push(
new TerserPlugin({
// cache: true,
parallel: true,
// sourceMap: true
})
)
}
else {
// Development plugins
}
module.exports = smp.wrap({
mode : isNotDevEnv ? 'production' : 'development',
target: ['web', 'es5'],
experiments: {
asset: true
},
devtool: isNotDevEnv ? false : 'source-map',
context: sourcePath,
entry: {
js: ['react-hot-loader/patch','./index.js'],
},
output: {
path: buildPath,
publicPath: '/',
filename: "bundle.js",
assetModuleFilename: '[path][name].[ext]'
},
module: {
rules,
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx', '.md', '.scss', '.css'],
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
fallback: {
"buffer": require.resolve('buffers'),
"assert": require.resolve('assert/'),
"fs": false,
"os": false,
"path": false,
"zlib": require.resolve('browserify-zlib'),
"stream": require.resolve('stream-browserify'),
"crypto": false,
} ,
},
plugins,
optimization : {
moduleIds: 'named',
sideEffects: isProdEnv,
},
devServer: {
contentBase: isNotDevEnv ? buildPath : sourcePath,
historyApiFallback: true,
port: 8080,
compress: isNotDevEnv,
inline: !isNotDevEnv,
hot: !isNotDevEnv,
host: "localhost",
disableHostCheck: true,
stats: {
assets: true,
children: false,
chunks: false,
hash: false,
modules: false,
publicPath: false,
timings: true,
version: false,
warnings: true,
colors: {
green: '\u001b[32m',
},
},
},
});
Here is my babel.config.json file:
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": "3",
"targets": {
"browsers": ["last 5 versions", "ie >= 9"]
}
}
],
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
["#babel/plugin-proposal-decorators", { "legacy": true }],
"react-hot-loader/babel",
"#babel/plugin-transform-arrow-functions",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-class-properties",
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
at the start of my src/index.js
there is that :
require('es6-promise/auto')
require('string.prototype.startswith')
require('string.prototype.endswith')
import 'react-app-polyfill/ie11';
import "react-app-polyfill/stable";
import "core-js/stable";
import "regenerator-runtime/runtime";
in my package.json I added that:
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all",
"IE 11"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version",
"IE 11"
]
},
Thank you !

webpack5 configuration don't works

this is kind of frustrating issue.
I've been trying to build my own "react-scripts" bundle, so my company no longer relies on it. This is something ordered from the heads, in order to reduce licenses and external dependencies.
I've tried the following webpack configurations:
Mine's (paths are hidden):
{
"mode": "development",
"devtool": "cheap-module-source-map",
"entry": {
"app": "./src/index.js"
},
"output": {
"filename": "[name].js",
"path": ".../static",
"publicPath": "/"
},
"optimization": {
"minimize": false
},
"resolve": {
"symlinks": false,
"extensions": [
".js",
".mjs",
".json"
],
"alias": {
"#": ".../src"
}
},
"module": {
"rules": [
{
"test": {},
"loader": "babel-loader",
"exclude": {},
"include": [
".../src",
".../node_modules/webpack-dev-server/client"
],
"type": "javascript/auto",
"options": {
"babelrc": false,
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": false
}
],
[
"#babel/plugin-proposal-private-methods",
{
"loose": false
}
],
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-transform-runtime"
],
"env": {
"test": {
"plugins": [
"istanbul"
]
}
}
}
},
{
"test": {},
"exclude": {},
"use": [
{
"loader": "style-loader"
},
{
"loader": "css-loader",
"options": {
"sourceMap": true
}
},
{
"loader": "postcss-loader",
"options": {
"plugins": [
null,
null,
null
]
}
},
{
"loader": "less-loader",
"options": {
"sourceMap": true
}
}
]
},
{
"test": {},
"loader": "url-loader",
"options": {
"limit": 10000,
"name": "images/[name].[hash:7].[ext]"
}
},
{
"test": {},
"loader": "url-loader",
"options": {
"limit": 10000,
"name": "media/[name].[hash:7].[ext]"
}
},
{
"test": {},
"loader": "url-loader",
"options": {
"limit": 10000,
"name": "fonts/[name].[hash:7].[ext]"
}
}
]
},
"plugins": [
{
"key": "ESLintWebpackPlugin",
"options": {
"extensions": "js",
"emitError": true,
"emitWarning": true,
"failOnError": true
}
},
{
"definitions": {
"ENVIRONMENT": "\"development\""
}
},
{
"userOptions": {
"filename": "index.html",
"template": "index.html",
"inject": true,
"minify": false
},
"version": 5
},
{
"patterns": [
{
"from": ".../static",
"to": "",
"globOptions": {
"ignore": [
".*"
]
}
}
],
"options": {}
},
{
"options": {}
},
{}
],
"devServer": {
"host": "localhost",
"port": 8080,
"clientLogLevel": "warning",
"hot": true,
"contentBase": false,
"compress": true,
"historyApiFallback": {
"rewrites": [
{
"from": {},
"to": "/index.html"
}
]
},
"open": false,
"overlay": {
"warnings": false,
"errors": true
},
"publicPath": "/",
"proxy": {},
"quiet": true,
"watchOptions": {
"poll": false
}
}
}
Demo setup I've found through the Internet:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const EslintWebpackPlugin = require('eslint-webpack-plugin');
const eslintConfig = require(path.resolve('...'));
eslintConfig.globals.React = true;
module.exports = {
entry: {
app : './src/index.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
devServer: {
port: 8080,
watchContentBase: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules\/(?!(?:...))(\?.*)?$/gi,
include:[
path.resolve('src')
],
use: {
loader: 'babel-loader',
options : {
babelrc: false,
presets : [ '#babel/preset-env', '#babel/preset-react' ]
}
}
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
}
]
},
plugins: [
new EslintWebpackPlugin({
context : path.resolve('src'),
overrideConfig: eslintConfig
}),
new HtmlWebpackPlugin({ template: path.resolve('index.html'), inject : true })
],
}
When I run npx webpack serve with my configuration, seems that content is not injected into index template so I get:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>
When I run the same but using demo configuration, it works as expected.
NOTE: After fixing some issues, bundling works, but running dev server still doesn't.

bundle.js still contains arrow function and default parameters after using babel pollyfill

I have added many settings given by Babel or others from stack overflow but the new features of ES6 such as arrow function and default parameter are still in my bundle.js
The bundle.js has content like below:
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] && (a[e] = `${t[e]} ${n[e]}`)
}
),
a
};
As a result, when I open my page in IE11, the error missing ')' happened which point to function(e={}).
Here is my webpack.config.js:
const entries = require("./config/pages").reduce(function(map, page) {
map[page] = `./src/${page}/index.js`;
return map;
}, {});
module.exports = {
mode: 'development',
entry: ["#babel/polyfill",...entries],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
and ./config/loaders for module
module.exports = {
rules: [
{
test: /\.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
the .babelrc:
{
"presets": [
// ["#babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"#babel/react"
],
"plugins": [
["#babel/transform-runtime"],
["#babel/plugin-transform-parameters"],
["#babel/plugin-transform-arrow-functions"],
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
Also, I have imported '#babel/polyfill' in my index.js
PS: I have noticed that the code contains ES6 features is from Meterial UI lib in node_modules, so I deleted exclude: /node_modules/, in babel loader rule but it still does not work.
I am using webpack 5, and setting target to es5 in webpack.config.js solved the problem for me.
module.exports = {
target: 'es5',
...
}
We are targeting specific browsers in the #babel/preset-env plugin, defined in the babel.config.js (which is a another way of declaring the babel configuration).
presets: [
[
'#babel/preset-env',
{
modules: 'commonjs',
useBuiltIns: 'entry',
targets: {
chrome: '58',
firefox: '54',
ie: '11',
safari: '10',
opera: '44',
edge: '16'
}
}
],
[
'#babel/preset-react'
]
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-proposal-class-properties'
]
Please try the target declaration like I posted above.
We use babel/preset-env 7.3.1 and it's corejs is not a top-level config option.
Update
I was able to make it work with a test project of which I tried to match your setup as best as possible. You can use this to slowly add complexity and modules that you use in your project to isolate the problem. This basic setup matches yours and works well. You can use this as a starting point.
package.json
{
"name": "babel-transprile-error",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"#babel/core": "^7.4.3",
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/plugin-proposal-decorators": "^7.4.0",
"#babel/plugin-transform-arrow-functions": "^7.2.0",
"#babel/plugin-transform-parameters": "^7.4.3",
"#babel/plugin-transform-runtime": "^7.4.3",
"#babel/polyfill": "^7.4.3",
"#babel/preset-env": "^7.4.3",
"#babel/preset-react": "^7.0.0",
"#babel/runtime": "^7.4.3",
"babel-loader": "^8.0.5",
"mini-css-extract-plugin": "^0.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1"
}
}
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: ["#babel/polyfill", './src/page/index.js'],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders.js"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
.babelrc
{
"presets": [
// ["#babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"#babel/react"
],
"plugins": [
["#babel/transform-runtime"],
["#babel/plugin-transform-parameters"],
["#babel/plugin-transform-arrow-functions"],
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
src/page/index.js
import React, { Component } from 'react';
class someComponent extends React.Component {
constructor(props) {
super(props);
}
method(e = {}) {
console.log(e);
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] && (a[e] = `${t[e]} ${n[e]}`)
}
), a
};
}
render() {
return (
<div onClick={ e => { this.method(e) }}/>
)
}
}
export default someComponent;
config/loaders.js
module.exports = {
rules: [
{
test: /\.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
In my case, it caused by some packages that contains default parameters. So I fixed that by include node_modules in babel-loader:
{
test: /\.(jsx?)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/env', '#babel/react'],
plugins: [
'#babel/plugin-transform-runtime',
[
'#babel/plugin-proposal-class-properties',
{
loose: true
}
],
['#babel/plugin-proposal-export-default-from'],
'#babel/plugin-transform-parameters'
]
}
}
/** Include the node_modules folder to fix !! **/
// exclude: /node_modules/ // <== Here is the magic works !
},

Resources