Babel-loader adds "require" statements due to "useBuiltIns: usage ", webpack transcribes them into import statements but doesn't resolve them.
Resulting in the following inside bundle.js and an error in the browser:
import "core-js/modules/es6.function.name"
I am using script-laoder to bundle them, which evals each file as string.
I just don't know how to tell webpack/script-loader to remove the import statements and include the modules in the bundle.
webpack.config.js:
module.exports = {
mode: "production",
resolve: {
modules: ['node_modules'],
extensions: ['.js']
},
entry: {
website: [
jsPath("babel-helpers.js"), // generated from babeL
jsPath('testfolder/test.js'),
]
},
module: {
rules: [ //executed bottom to top!
{
test: /\.js$/,
use: [ 'script-loader' ]
},
{
test: /\.ajs$/,
exclude: [/\.min\.js$/, /node_modules/],
use: {
loader: 'uglify-es-loader',
options: {
//parse: {},
//compress: {},
//mangle: true, // Note `mangle.properties` is `false` by default.
}
}
},
{
test: /\.js$/,
exclude: [/\.min\.js$/, /node_modules/, /babel-helpers/], // exclude babel-helpers or error.
loader: 'babel-loader',
// options: { //uses config from .babelrc file when not specified here.
// presets: ['#babel/preset-env']
// }
},
{
test: /\.js$/,
exclude: [/\.min\.js$/, /node_modules/, /babel-helpers/],
loader: 'string-replace-loader',
options: {
multiple: [
{ search: 'process.env.NODE_ENV', replace: JSON.stringify('production') },
]
}
}
]
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, jsFolder),
libraryTarget: 'umd',
library: 'add'
}
};
package.json
"#babel/core": "^7.5.5",
"#babel/preset-env": "^7.5.5",
"#babel/plugin-external-helpers": "^7.2.0",
"babel-loader": "^8.0.6",
"script-loader": "^0.7.2",
"string-replace-loader": "^2.2.0",
"uglify-es-loader": "^3.0.4",
"webpack": "^4.36.1",
"webpack-cli": "^3.3.6"
.babelrc
{
"presets": [
[
"#babel/env",
{
"useBuiltIns": "usage",
"targets":
{
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1",
"ie": "11"
}
}
]
],
"plugins": [
"#babel/plugin-external-helpers"
]
}
Related
I have a problem in a vue project I have I´m in the process of breaking out components into a components library.
i get this error message when i consume components from my local components library.
Uncaught TypeError: Cannot read properties of undefined (reading 'fd')
at Function.useColors
looking where that is in the code i find this
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty__default["default"].isatty(process.stderr.fd);
}
and a litle googling later it is my understanding is that this code is debug-js for node and that other people have gotten the same error in the past. The solution in the old thread is something with babeland how to resolve modules but i do not seem to be able to find out how to do it for rollup.
Manipulating the bundled code manually so the function returns false makes the code run with no problem but i really do not want to do that
How can I fix this the right way. It seems like I miss something super basic that i for some reason cant find the answer to.
package.json
{
"name": "local-vue-components",
"version": "0.1.0",
"main": "lib/index.js",
"module": "lib/index.esm.js",
"scripts": {
"build": "rollup -c"
},
"peerDependencies": {
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2"
},
"dependencies": {
"local-library":"*"
},
"devDependencies": {
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2",
"#rollup/plugin-commonjs": "^14.0.0",
"#rollup/plugin-node-resolve": "^8.4.0",
"#rollup/plugin-json":"^5.0.1",
"#vue/compiler-sfc": "^3.0.0-rc.5",
"rollup": "^2.23.1",
"rollup-plugin-peer-deps-external": "^2.2.3",
"rollup-plugin-typescript2": "^0.27.2",
"rollup-plugin-vue": "^5.1.6",
"typescript": "^3.9.7",
"vue-template-compiler": "^2.6.11"
}
}
rollup.config.js
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";
import json from "#rollup/plugin-json";
import packageJson from "./package.json";
export default {
input: "src/index.ts",
output: [
{
format: "cjs",
file: packageJson.main,
sourcemap: true
},
{
format: "esm",
file: packageJson.module,
sourcemap: true
}
],
plugins: [peerDepsExternal(), resolve(), commonjs(), typescript(),json(),vue()]
};
I realise it can also be a problem with the consuming project that uses babel and Webpack with the configs below.
babelrc.js
module.exports = function (api) {
const presets = [
'#babel/preset-env',
{
targets: {
chrome: "70"
}
}
];
return presets;
}
webpack.js
const path = require("path");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
require("#babel/register");
module.exports = {
entry: {
babelPollyfill: "#babel/polyfill",
jprApp: "./src/app/main.ts",
'
},
resolve: {
extensions: [".js", ".ts", ".json"],
mainFields: ["browser", "main"],
alias: {
vue$: "vue/dist/vue.esm.js"
}
},
module: {
rules: [
{
test: /\.(css)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
}
}, {
loader: 'extract-loader'
}, {
loader: 'css-loader',
}, {
loader: 'postcss-loader',
}
]
},
{
enforce: "pre",
use: ["source-map-loader"],
test: /\.js$/
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: [/node_modules/,/__test__/]
},
{
test: /\.render\.js$/,
use: ["file-loader"]
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
}
}
]
},
output: {
publicPath: "",
filename: "[name].js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new NodePolyfillPlugin(),
]
};
I'm dealing with an issue I'm having when trying to run my local dev environment. I'm using Webpack 2 and Babel 6.
I can't seem to figure out how to get a package that contains empty catches to parse.
Is there a plugin for Babel to do so? Do I need to do something else?
[0] Module parse failed: C:\Users\PROJECT\node_modules\ssh2\lib\server.js Unexpected token (490:16)
[0] You may need an appropriate loader to handle this file type.
[0] | try {
[0] | socket.end();
[0] | } catch {} << it's complaining about this section.
[0] | },
.babelrc file:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["add-module-exports"],
"env": {
"production": {
"presets": ["react-optimize"],
"plugins": [
"babel-plugin-transform-remove-console",
"babel-plugin-transform-remove-debugger",
"babel-plugin-dev-expression",
"add-module-exports"
]
},
"development": {
"plugins": ["transform-exponentiation-operator"]
},
"test": {
"plugins": [
[
"webpack-loaders",
{
"config": "webpack.config.node.js",
"verbose": false
}
],
[
"babel-plugin-module-alias",
{
"src": "test/electron/mockElectron",
"expose": "electron"
}
]
]
}
}
}
Webpack dev config:
/* eslint max-len: 0 */
import webpack from 'webpack';
import baseConfig from './webpack.config.base';
const config = {
...baseConfig,
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr',
'#babel/polyfill',
'./app/index'
],
output: {
...baseConfig.output,
publicPath: 'http://localhost:3000/dist/'
},
module: {
...baseConfig.module,
loaders: [
...baseConfig.module.loaders,
{
test: /\.global\.css$/,
loaders: [
'style-loader',
'css-loader?sourceMap'
]
},
{
test: /^((?!\.global).)*\.css$/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
]
}
]
},
plugins: [
...baseConfig.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
target: 'electron-renderer'
};
export default config;
Webpack base config:
import path from 'path';
import WebpackNotifierPlugin from 'webpack-notifier';
export default {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.cjs?$/,
loaders: ['babel-loader']
}
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'commonjs2'
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.cjs'],
mainFields: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
},
plugins: [
new WebpackNotifierPlugin({excludeWarnings: true})
],
externals: [
]
};
Relevant packages:
"#babel/core": "^7.9.0",
"#babel/plugin-transform-exponentiation-operator": "7.18.6",
"#babel/plugin-proposal-optional-catch-binding": "^7.18.6",
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.19.0",
"#babel/preset-react": "^7.18.6",
"#babel/preset-stage-0": "^7.8.3",
"#babel/register": "^7.18.9",
"#babel/parser": "^7.19.0",
"#babel/eslint-parser": "^7.18.9",
"#babel/eslint-plugin": "7.18.10",
"babel-loader": "8.0.0",
"babel-plugin-add-module-exports": "1.0.4",
"babel-plugin-dev-expression": "0.2.1",
"babel-plugin-module-alias": "1.6.0",
"babel-plugin-transform-react-inline-elements": "7.0.0-beta.3",
"babel-plugin-transform-remove-console": "^6.9.4",
"babel-plugin-transform-remove-debugger": "^6.9.4",
"babel-plugin-webpack-loaders": "0.9.0",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-react-optimize": "1.0.*",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "~10.1.0",
"webpack": "2.7.0",
"webpack-dev-middleware": "2.0.6",
"webpack-hot-middleware": "2.25.2"
The package that causes the issue is ssh2 post 0.8.9. Any version from 1.0.0 onwards. From 1.0.0 the files seem to have a number of catch {} occurrences.
Im trying to setup a new js/typescript environment to practice web dev while using react, yarn, and webpack but I keep getting this error when trying to get it set up. My current configs look like this. I am new to all of this so if you see anything I should change then please let me know.
webpack.config.js
const path = require('path')
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
entry: path.resolve(__dirname, './src/index.js'),
resolve: {
extensions: ['*', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react'],
},
},
],
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [require('precss'), require('autoprefixer')]
},
},
},
{
loader: 'saas-loader',
},
],
exclude: /node_modules/,
},
],
},
output: {
filename: 'bundle.js',
},
}
index.js
import React from 'react'
import {render} from 'react-dom'
import 'bootstrap/dist/css/bootstrap.css'
import Counter from './components/counter.jsx'
ReactDOM.render(<Counter />, document.getElementById('app'))
package.json
{
"name": "trend-dot-com",
"version": "1.0.0",
"main": "index.js",
"license": "TBA",
"devDependencies": {
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"bootstrap": "^4.5.0",
"postcss-loader": "^3.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass-loader": "^8.0.2"
},
"scripts": {
"watch": "webpack-dev-server --progress"
}
}
Thanks in advance!
On the first look everything looked Ok. But the problem seems to be in your webpack.config file.
Try below
const path = require('path')
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
entry: path.resolve(__dirname, './src/index.js'),
resolve: {
extensions: ['*', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use:
{
loader: 'babel-loader',
options: {
presets:["#babel/preset-env","#babel/preset-react" ]
},
},
},
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [require('precss'), require('autoprefixer')]
},
},
},
{
loader: 'saas-loader',
},
],
exclude: /node_modules/,
},
],
},
output: {
filename: 'bundle.js',
},
}
Also after changing this there is a css-loader error which is not installed , so you can install and add that to your package.json. But since you already have Sass packages may be you want to refer the bootstrap sass version in your index.js - upto you. Hope this helps!.
I am trying my hands on Webpack4/Redux/React and getting the following error for my sample application:
./src/index.js] 210 bytes {main} [built] [failed] [1 error]
+ 13 hidden modules
ERROR in ./src/index.js Module parse failed: Unexpected token (3:16)
You may need an appropriate loader to handle this file type. | import
React from 'react'; | | const element = Hello, world; | | #
multi webpack-dev-server/client?http://localhost:3000
webpack/hot/only-dev-server ./src/index i 「wdm」: Failed to compile.
I have tried different ways to resolve this (as is evident from commented out code) without any success. Please let me know what I am missing. My Code files are as follows:
Package.json:
{
"name": "react-redux-example",
"version": "1.0.0",
"description": "using redux architecture",
"main": "node server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git"
},
"keywords": [
"reactjs",
"redux",
"react",
"hot",
"reload",
"live",
"edit",
"webpack"
],
"author": "newbieToReact",
"license": "MIT",
"dependencies": {
"babel": "^6.23.0",
"mkdirp": "^0.5.1",
"react": "^16.4.0",
"react-router": "^4.2.0",
"style-loader": "^0.21.0",
"webpack": "^4.10.2",
"webpack-dev-server": "^3.1.4"
},
"devDependencies": {
"extract-text-webpack-plugin": "^4.0.0-beta.0"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'true'))
});
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
mode: "development",
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
//new webpack.NoErrorsPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
devFlagPlugin,
new ExtractTextPlugin('app.css')
],
// module: {
// loaders: [
// {
// test: /\.jsx?$/,
// loaders: ['react-hot', 'babel'],
// include: path.join(__dirname, 'src')
// },
// { test: /\.css$/, loader: ExtractTextPlugin.extract('css-loader?module!cssnext-loader') }
// ]
// },
//module: {
// rules: [
// {
// exclude: '/node_modules/',
//test: /\.jsx?$/,
//test: /\.js$/,
// test: /\.(js|jsx)$/,
// include: path.join(__dirname, 'src'),
// test: /\.css$/,
// use: [
// { loader: "react-hot" },
// { loader: "babel" },
// { loader: "ExtractTextPlugin.extract('css-loader?module!cssnext-loader')"},
// { loader: "style-loader" },
// ]
// }
// ]
// },
module: {
rules: [
{
exclude: '/node_modules/',
test: /\.(js|jsx)$/,
include: path.join(__dirname, 'src'),
test: /\.css$/,
loader: "react-hot",
loader: "babel",
loader: "ExtractTextPlugin.extract('css-loader?module!cssnext-loader')",
loader: "style-loader",
}
]
},
resolve: {
extensions: ['.js', '.json']
}
};
src/index.js
import React from 'react';
const element = <h1>Hello, world</h1>;
Your module/loaders needs another clause in test: this needs to be test: /\.(js|jsx)$/, because you are using a .js file and no .jsx. Also it's a good practice to include this in your config: resolve: { extensions: ['.js'] }, when using .js instead off .jsx. Also uncomment the second loader because i see you're using a .css this needs the css-loader to work.
You will have to add css-loader and babel-loader to your devDependencies aswell.
Also you're using webpack 4 which implies that ExtractTextPlugin has been deprecated so remove this.
Hope this helped, good luck!
In webpack.config.js you should follow scheme described in webpack docs
Here is an example
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
}, {
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}]
After webpack command webpack catch all files and finish build in dist folder, but react component doesn't work. I don't understand why. My configs attached:
package.json
{
"name": "name",
"version": "1.0.0",
"description": "Example",
"main": "index.js",
"scripts": {
"watch": "webpack --progress --watch",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"devDependencies": {
"autoprefixer": "^7.1.3",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.16",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"node-sass": "^4.5.3",
"optimize-css-assets-webpack-plugin": "^3.1.1",
"postcss-loader": "^2.0.6",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
},
"browserslist": [
"last 15 versions",
"> 1%",
"ie 8",
"ie 7"
]
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: ['./app/app.js', './app/sass/app.sass'
],
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "postcss-loader"]
}),
},
{
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract(['css-loader', 'postcss-loader', 'sass-loader'])
},
{
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
name: 'img/[name].[ext]', // check the path
}
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]', // check the path
}
}
}
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Build version'
}),
new ExtractTextPlugin({
filename: 'css/app.min.css',
allChunks: true,
}),
new OptimizeCssAssetsPlugin()
]};
babel.rc
{"presets":["es2015", "react"]}
app file system:
app/
components/
fonts/
img/
sass/
app.js
index.html
index.html has a <div> with id="app" and script with src="app.js" in the body.
Move react and react-dom to dependencies instead of devDependecies in your package.json then try to build again.
Check this answer for an explanation:
Bower and devDependencies vs dependencies
Your react and react-dom packages are dependencies try moving them there.
Try modifying your webpack config file to some like this:
module.exports = {
entry: [
'./app/app.js',
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
publicPath: '/dist',
sourceMapFilename: 'bundle.map',
},
devtool: process.env.NODE_ENV === 'production' ? undefined : 'cheap-module-eval-source-map',
resolve: {
modules: ['node_modules', './app/components'],
extensions: ['.js', '.jsx'],
},
module: {
loaders: [
{
test: /(\.js$|\.jsx$)/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react', 'es2015'],
},
},
],
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compressor: {
warnings: false,
},
})
],
};
Add other necessary rules you need to the rules array.
With this config though, you don't need the .babelrc file as everything is all in place.