Babel doesn't process node_modules - no excludes, no .babelrc - javascript

This has been asked multiple times, and the issues always comes down to either a presence of exclude in babel config, or babel config being in .babelrc instead of babel.config.json. In my case it's something else. Here's my babel.config.json:
{
"presets": [
[
"#babel/preset-react",
{
"runtime": "automatic"
}
],
"#babel/env"
],
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
[
"module-resolver",
{
"alias": {
"#common": "./src/common",
"#files": "./src/files",
"#settings": "./src/settings",
}
}
]
]
}
Here's my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ENV = process.env;
const scriptDir = path.join(__dirname, 'scripts');
const config = {
devtool: ENV.WEBPACK_DEVTOOL || 'eval-source-map',
mode: 'development',
entry: {
app: ['./src/app.js'],
},
output: {
path: scriptDir,
publicPath: '/',
},
target: ['web', 'es5'],
module: {
rules: [
{
test: path.resolve(__dirname, 'node_modules/ajv'),
use: 'null-loader',
},
{
test: /\.(js|cjs|jsx)$/,
use: ['babel-loader'],
include: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules/nanoid')],
},
{
test: /\.json$/,
use: ['json-loader'],
type: 'javascript/auto',
},
{
test: /\.css/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.min\.js$/,
exclude: [/react/, /node_modules/],
use: ['script-loader'],
},
{
test: /node_modules\/vfile\/core\.js/,
use: [
{
loader: 'imports-loader',
options: {
type: 'commonjs',
imports: ['single process/browser process'],
},
},
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(ENV.NODE_ENV),
}),
],
resolve: {
symlinks: false,
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
'#common': path.resolve(__dirname, './src/common'),
'#files': path.resolve(__dirname, './src/files'),
'#settings': path.resolve(__dirname, './src/settings'),
},
fallback: {fs: false, path: require.resolve('path-browserify')},
},
};
if (ENV.NODE_ENV === 'production') {
config.devtool = 'hidden-source-map';
config.mode = 'production';
}
if (ENV.WEBPACK_PLUGIN) {
const Plugin = require(ENV.WEBPACK_PLUGIN);
config.plugins.push(new Plugin());
}
module.exports = config;
When I run the output bundle in IE11, I'm seeing an arrow function, and it comes specifically from package nanoid. As you see above, I tried to explicitly include it. Tried without the include as well.
I'm on Babel 7.12 and Webpack 5.4.
So what is still missing in the config? Why is babel still refusing to parse (some of the) node_modules?

The solution was either to remove the include as suggested by #loganfsmyth in the comments above, or to set include to something more general:
include: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')]

Related

Unknown word error in css file even with css-loader

I am getting a syntax error in one of my css files from monaco-editor in node_modules. It is an unknown word error:
> 1 | // Imports
| ^
2 | import ___CSS_LOADER_API_IMPORT___ from "../../../../../../css-loader/dist/runtime/api.js";
3 | var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(function(i){return i[1]});
# ./node_modules/monaco-editor/esm/vs/platform/contextview/browser/contextMenuHandler.css 2:12-317 9:17-24 13:15-29
However, I have css-loader configured in my webpack.config.js:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const PerspectivePlugin = require("#finos/perspective-webpack-plugin");
const path = require("path");
const plugins = [
new HtmlWebPackPlugin({
title: "Perspective React Example",
template: "./src/frontend/index.html",
}),
new PerspectivePlugin(),
];
module.exports = {
context: path.resolve(__dirname),
entry: "./src/frontend/index.tsx",
mode: "development",
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
plugins: plugins,
module: {
rules: [
{
test: /\.ts(x?)$/,
//exclude: /node_modules/,
loader: "ts-loader",
},
{
test: /\.css$/,
//exclude: /node_modules/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 1,
},
},
'postcss-loader'
],
},
],
},
devServer: {
// superstore.arrow is served from here
contentBase: [
path.join(__dirname, "dist"),
path.join(__dirname, "node_modules/superstore-arrow"),
],
},
experiments: {
executeModule: true,
syncWebAssembly: true,
asyncWebAssembly: true,
},
output: {
filename: "app.js",
path: __dirname + "/dist",
},
};
I also have a config file for postcss-loader:
module.exports = {
plugins: [
require('autoprefixer')
]
};
I'm not sure what is wrong with what I'm doing, so I'm wondering if there is another loader I need to add to webpack.config.js or if my configuration is incorrect?
I had same issue, try this:
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"postcss-preset-env",
{
// Options
},
],
],
},
},
},
],

How to ignore error js script tag from html on running webpack with HtmlWebpackPlugin?

How can i ignore the script tag in Html webpack plugin?
Because I have added this
<script src="cordova.js"/>
tag into my index.html template anonymously for my app development.
See my configuration in Webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "www"),
filename: "./js/build/[name].build.js",
chunkFilename: "./js/build/[name].build.js",
// publicPath: "./js/build/",
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./",
},
},
"css-loader?url=false",
"sass-loader",
],
},
{
test: /\.html$/,
use: ["html-loader"],
},
{
test: /\.(svg|png|jpeg|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "res",
},
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "./css/build/[name].css",
// chunkFilename: "../css/[id].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
// new BundleAnalyzerPlugin()
],
// devtool: "inline-source-map",
};
I just wanted to ignore the script on production and I have researched this many times but unfortunately I don't see any solution
So, if I got the problem right, you want to ignore a certain resource when bundling for production.
The html-loader has an option to filter sources based on attribute, attribute value, context file and anything you have available in you webpack.config.js.
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Assuming you are passing arguments to your webpack config like argv.mode
const PRODUCTION = true;
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "www"),
filename: "./js/build/[name].build.js",
chunkFilename: "./js/build/[name].build.js",
// publicPath: "./js/build/",
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./",
},
},
"css-loader?url=false",
"sass-loader",
],
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: {
sources: {
urlFilter: (attribute, value, resourcePath) => {
if (PRODUCTION && /cordova.js$/.test(value)) {
return false;
}
return true;
},
}
},
},
},
{
test: /\.(svg|png|jpeg|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "res",
},
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "./css/build/[name].css",
// chunkFilename: "../css/[id].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
// new BundleAnalyzerPlugin()
],
// devtool: "inline-source-map",
};
In the html module rule, I added an options property to html-loader with an example how you could ignore a certain resource with urlFilter. Check the html-loader docs on filtering resources
You will need to get a reference to the variables you passed to your cli like --mode eg. line 5-6. (Not in the current example) See webpack docs on env vars.

Getting Unexexpted token caused error due to loader when using Stripe checkout

I am trying to integrate Stripe checkout into a VueJS application, but get the following error when the app compiles;
ERROR in ./node_modules/stripe/lib/utils.js
Module parse failed: Unexpected token (152:24)
You may need an appropriate loader to handle this file type.
| opts.auth = args.pop();
| } else if (utils.isOptionsHash(arg)) {
| const params = {...args.pop()};
|
| const extraKeys = Object.keys(params).filter(
# ./node_modules/stripe/lib/stripe.js 44:14-32
# ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/app/CMS/eCommerce/Checkout.vue
# ./src/app/CMS/eCommerce/Checkout.vue
# ./src/routes.js
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8082 webpack/hot/dev-server ./src/main.js
I happens when i add the following variable to mt Checkout.vue file;
import Stripe from 'stripe';
const stripe = Stripe('MYAPI');
Here is we webpack file
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
filename: 'build.js',
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'style-loader',
'css-loader'
],
},
{
test: /\.html$/i,
loader: 'html-loader',
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
outputPath: 'assets/images/'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true,
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Any advice would be great. Thank you
It seems to me like something went wrong in the file ./src/app/CMS/eCommerce/Checkout.vue.
First: Do both variables arg and args really exist?
Second: In order for the syntax params = {...args.pop()} to work argsmuss be an array of objects
Third: Do you have a babel config file? Because I think you need the babel preset "#babel/preset-env" or some babel plugins like "#babel/plugin-proposal-object-rest-spread" and "#babel/plugin-transform-spread" for babel to transpile the code for the browser...
A minimal babel.config.js can look like this:
module.exports = api => {
api.cache(true);
const presets = [];
const plugins = [];
/*
// If you want to transpile just some syntaxes manually - micromanagement
plugins.push(
[ "#babel/plugin-transform-block-scoping" ],
[ "#babel/plugin-proposal-object-rest-spread" ],
[ "#babel/plugin-transform-classes" ],
[ "#babel/plugin-transform-spread" ],
[ "#babel/plugin-transform-destructuring" ],
[ "#babel/plugin-transform-for-of" ],
[ "#babel/plugin-transform-template-literals" ],
[ "#babel/plugin-transform-arrow-functions", { spec: false } ],
);
*/
// Or let babel transpile everthing
presets.push(
[ "#babel/preset-env" ]
)
return {
presets,
plugins
}
}

Adding a csv file to a webpack build

I have placed a csv file in my assets folder for my react app, however, that file is not getting picked up and added to my dist build via webpack (the images are still added as assets to the build but the csv file is not). You can see my webpack build below. So how do I add a csv file to my dist build via webpack (the goal is for users of my app to be able to download this file)? Thanks!
webpack.dev.js
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const config = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
historyApiFallback: true,
hot: true,
proxy: {
'/api': {
target: 'http://localhost:5001',
secure: false,
},
},
allowedHosts: [
'localhost',
'fatpandadev'
],
public: 'fatpandadev:8080'
},
});
module.exports = config;
webpack.common.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const DIST_DIR = path.resolve(__dirname, "dist");
const SRC_DIR = path.resolve(__dirname, "src");
const config = {
entry: [
"babel-polyfill",
`${SRC_DIR}/app/index.js`,
`${SRC_DIR}/app/assets/stylesheets/application.scss`,
`${SRC_DIR}/app/components/index.scss`,
"font-awesome/scss/font-awesome.scss",
"react-datepicker/dist/react-datepicker.css",
"rc-time-picker/assets/index.css",
"react-circular-progressbar/dist/styles.css",
"#trendmicro/react-toggle-switch/dist/react-toggle-switch.css",
],
output: {
path: `${DIST_DIR}/app/`,
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
failOnWarning: false,
failOnError: true
}
},
{
test: /\.js$/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'stage-2']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: ['file-loader?context=src/images&name=images/[path][name].[ext]', {
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}],
exclude: path.resolve(__dirname, "node_modules"),
include: __dirname,
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// loader: "url?limit=10000"
use: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader'
},
{
test: /\.(txt|csv)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "application.css"
})
]
};
module.exports = config;
(this answer is only referenced on the server side)
In addition to #PlayMa256,
On Server side(Nodejs runtime), you may need emitFile: true
{
test: /\.(txt|csv|mmdb)$/,
use: [
{
loader: 'file-loader',
options: {
name: "[path][name].[ext]",
emitFile: true,
},
},
],
},
Refer to this PR: https://github.com/webpack-contrib/file-loader/pull/135
In my opinion, file-loader way seem to better than copy-webpack-plugin way.
You can test like below:
import csvPath from './assets/data.csv'
console.log(csvPath) // assets/data.csv
Tested version:
$ cat node_modules/webpack/package.json | jq .version
"4.29.5"
$ cat node_modules/file-loader/package.json | jq .version
"3.0.1"
You might want to check the CopyWebpackPlugin if you have no need to process/parse the files, but only to copy them to your dist folder.
Copy Webpack Plugin
Copies individual files or entire directories to the build directory
Install
npm i -D copy-webpack-plugin
Usage
webpack.config.js
const CopyWebpackPlugin = require('copy-webpack-plugin')
const config = {
plugins: [
new CopyWebpackPlugin([ ...patterns ], options)
]
}
Patterns
A simple pattern looks like this
{ from: 'source', to: 'dest' }
{
test: /\.(txt|csv)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
You should import you csv file as you import your images too.
import your csv files using raw-loader,
{
test: /\.csv$/i,
use: 'raw-loader',
}

babel transpile to es5 doesnt work for node_modules

I am trying to run my current project in ie11, but it gives me an error saying SCRIPT1002: syntax error in foundation.js (its part of google's material design classes). The line in question is export default MDCFoundation. Now from what i have red the issue is that this is es6 code and ie11 only supports es5. So far so good. The problem now is I cant seem to figure out how to tell babel to transpile to es5. I am using webpack and babel, here is my webpack.config.js:
var path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var LiveReloadPlugin = require('webpack-livereload-plugin');
const autoprefixer = require('autoprefixer');
module.exports = {
entry:{
app: ['./src/app.js']
},
devtool: 'inline-source-map',
externals: /^(tables.)/i,
module: {
rules:
[
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
},
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader, // <---- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
}
}
],
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, // <--- added here
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()],
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['./node_modules'],
},
}
],
},
{
test: /\.js$/,
include: /src/,
loader: 'babel-loader',
options: {
"presets": [
["env", {
"targets": {
"browsers": ["ie >= 11"]
}
}]
]
}
}
],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'style.css'}),
new LiveReloadPlugin({}),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery' })
],
resolve: {
extensions: ['.js']
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
},
output: {
publicPath: './dist',
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
}
};
As you can see I am already trying to tell babel to transpile for ie11, but it still gives me the same error.

Categories

Resources