webpack5 configuration don't works - reactjs

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.

Related

Eslint and Babel parser throwing errors in React

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

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 !

Webpack + Linaria - Support for the experimental syntax 'jsx' isn't currently enabled

I added linaria to my webpack config in a create-react-app project, so the eventual rule is like so:
{
"test": /\.(js|mjs|jsx|ts|tsx)$/,
"include": "C:\\Project\\src",
"use": [
{
"loader": "C:\\Project\\node_modules\\babel-loader\\lib\\index.js",
"options": {
"customize": "C:\\Project\\node_modules\\babel-preset-react-app\\webpack-overrides.js",
"presets": [
[
"C:\\Project\\node_modules\\babel-preset-react-app\\index.js",
{ "runtime": "automatic" }
],
"C:\\Project\\node_modules\\#linaria\\babel-preset\\lib\\index.js"
],
"babelrc": false,
"configFile": false,
"cacheIdentifier": "production:babel-plugin-named-asset-import#0.3.7:babel-preset-react-app#10.0.0:react-dev-utils#11.0.4:react-scripts#4.0.3",
"plugins": [
[
"C:\\Project\\node_modules\\babel-plugin-named-asset-import\\index.js",
{
"loaderMap": {
"svg": {
"ReactComponent": "#svgr/webpack?-svgo,+titleProp,+ref![path]"
}
}
}
]
],
"cacheDirectory": true,
"cacheCompression": false,
"compact": true
}
},
{
"loader": "C:\\Project\\node_modules\\#linaria\\webpack-loader\\lib\\index.js",
"options": { "sourceMap": false, "cacheDirectory": "src/.linaria_cache" }
}
]
}
But I'm getting this as a result:
Support for the experimental syntax 'jsx' isn't currently enabled
Is there anything wrong with this config?
It seems #linaria\webpack-loader won't work without babelrc file (even though the presets are on babel-loader already)
{
"presets": [
"babel-preset-react-app",
"#linaria"
],
"plugins": [
[
"babel-plugin-named-asset-import",
{
"loaderMap": {
"svg": {
"ReactComponent": "#svgr/webpack?-svgo,+titleProp,+ref![path]"
}
}
}
],
"#babel/plugin-proposal-class-properties"
]
}

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 !
},

How to tell webpack to preprocess a yarn package with flow annotations?

I am currently having a client side application which uses React, flow types and I package it using webpack 3.11 and everything is working great so far.
Just because the app is starting to get a little too big, I decided to move some React components to their own package by moving them to their own folder, setting up a package.json and then installing them by doing yarn add ./path/to/package --dev and after that webpack started complaining because it could not parse my flow annotations.
Error example
Module parse failed: Unexpected token (15:7)
You may need an appropriate loader to handle this file type.
| import "./BaseTree.css";
|
| export type Tree = {
| name: NodeName,
| parent: ?NodeName,
I've read about compiling my assets and using the stripped down javascript in my app but that's an extra building step I'd rather avoid since I don't plan on using this package anywhere else and my webpack setup already handles flow types just fine on it's own.
.babelrc
{
"presets": [
[
"env",
{
"targets": {
"node": "current",
"browsers": ["last 3 versions"]
}
}
],
"jest",
"react",
"flow"
],
"plugins": ["transform-class-properties"]
}
webpack.config.js (as generated by #symfony/webpack-encore)
{
"context": "/vhosts/app",
"entry": {
"main": "./assets/modules/main.js",
},
"output": {
"path": "/vhosts/app/public/build",
"filename": "[name].js",
"publicPath": "/build/",
"pathinfo": true
},
"module": {
"rules": [
{
"test": {},
"exclude": {},
"use": [
{
"loader": "babel-loader",
"options": {
"cacheDirectory": true
}
}
]
},
{
"test": {},
"use": [
{
"loader": "/vhosts/app/node_modules/extract-text-webpack-plugin/dist/loader.js",
"options": {
"omit": 1,
"remove": true
}
},
{
"loader": "style-loader?sourceMap"
},
{
"loader": "css-loader",
"options": {
"minimize": false,
"sourceMap": true,
"importLoaders": 1
}
},
{
"loader": "postcss-loader",
"options": {
"sourceMap": true
}
}
]
},
{
"test": {},
"loader": "file-loader",
"options": {
"name": "images/[name].[hash:8].[ext]",
"publicPath": "/build/"
}
},
{
"test": {},
"loader": "file-loader",
"options": {
"name": "fonts/[name].[hash:8].[ext]",
"publicPath": "/build/"
}
}
]
},
"plugins": [
{
"filename": "[name].css",
"id": 1,
"options": {
"allChunks": false
}
},
{
"entriesToDelete": []
},
{
"opts": {
"basePath": "build/",
"publicPath": "/build/",
"fileName": "manifest.json",
"stripSrc": null,
"transformExtensions": {},
"writeToFileEmit": true,
"cache": null
}
},
{
"options": {
"debug": true,
"options": {
"context": "/vhosts/app",
"output": {
"path": "/vhosts/app/public/build"
}
},
"test": {}
}
},
{
"options": {}
},
{
"definitions": {
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
}
},
{
"paths": [
"**/*"
],
"options": {
"root": "/vhosts/app/public/build",
"verbose": false,
"allowExternal": false,
"dry": false
}
},
{
"definitions": {
"process.env": {
"NODE_ENV": "\"development\""
}
}
},
{
"compilationSuccessInfo": {
"messages": []
},
"shouldClearConsole": false,
"formatters": [
null,
null,
null,
null,
null,
null
],
"transformers": [
null,
null,
null,
null,
null,
null
]
},
{
"outputPath": "public/build",
"friendlyErrorsPlugin": {
"compilationSuccessInfo": {
"messages": []
},
"shouldClearConsole": false,
"formatters": [
null,
null,
null,
null,
null,
null
],
"transformers": [
null,
null,
null,
null,
null,
null
]
}
}
],
"devtool": "inline-source-map",
"performance": {
"hints": false
},
"stats": {
"hash": false,
"version": false,
"timings": false,
"assets": false,
"chunks": false,
"maxModules": 0,
"modules": false,
"reasons": false,
"children": false,
"source": false,
"errors": false,
"errorDetails": false,
"warnings": false,
"publicPath": false
},
"resolve": {
"extensions": [
".js",
".jsx",
".vue",
".ts",
".tsx"
],
"alias": {}
},
"externals": {}
}
TL;DR version
Have app written using flow types.
Also have own npm package written using flow types to be used just on that app.
Can I set up webpack so that it strips the types for both my app code and the package?

Resources