We're converting our gulpfile.js in node v13.8.0 to ES6 as following:
import { src, dest, series, parallel, watch } from 'gulp'
import nodemon from 'gulp-nodemon' // normal nodemon does not display an error on app crash
import env from 'gulp-env'
import browser from 'browser-sync'
import sass from 'gulp-sass'
// Tasks
export default {
cssTranspile: cssTranspile,
jsTranspile: jsTranspile,
server: series(startNodemon, startBrowserSync),
default: series(
parallel(
cssTranspile,
jsTranspile
),
startNodemon,
startBrowserSync,
function () {
watch('public/scss/*.scss', cssTranspile)
}
)
}
The error reported, when simply running gulp, is:
internal/modules/cjs/loader.js:1160
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: T:\Node\ICP\gulpfile.js
require() of ES modules is not supported.
I must be doing something wrong. Anyone an idea on what it might be?
CLI version: 2.2.0
Local version: 4.0.2
The flag "type": "module", is set in package.json as described in the note docs. The issue is very much similar to this issue in the geolib library.
And when we rename gulpfile.js to gulpfile.babel.js as described here we get the same error.
The package.json contain these packages:
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/register": "^7.8.3",
"exports-loader": "^0.7.0",
"gulp": "^4.0.2",
"gulp-env": "^0.4.0",
"gulp-nodemon": "^2.4.2",
"gulp-sass": "^4.0.2",
"nodemon": "^2.0.2"
},
"type": "module",
"babel": {
"presets": [
"#babel/env"
]
In an answer to my own question, when the flag "type": "module" is set in package.json you can't use gulp. More info can be found here.
This seems to be fixed now: https://github.com/gulpjs/gulp-cli/pull/214. Be sure to install the latest version of gulp-cli (2.3.0 as of June 2020).
If your package.json specifies "type": "module" you can name your ES module with Gulp tasks gulpfile.js, otherwise name it gulpfile.mjs. No need to use any transpilers or preloaders like esm, Babel or TypeScript.
Related
I am trying to test in React application with Jest; my application uses Vite as a module bundler. The issue is, every time I run tests I get the following error:
> react-test#0.0.0 test
> jest
FAIL src/test/App.test.jsx
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to
enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
SyntaxError: C:\Users\Tomas\Desktop\react-test\src\test\App.test.jsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:30):
6 |
7 | test("renders content", ()=>{
> 8 | const component = render(<App></App>)
| ^
9 | console.log(component)
10 | })
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
at Parser._raise (node_modules/#babel/parser/src/parser/error.js:150:45)
at Parser.raiseWithData (node_modules/#babel/parser/src/parser/error.js:145:17)
at Parser.expectOnePlugin (node_modules/#babel/parser/src/parser/util.js:214:18)
at Parser.parseExprAtom (node_modules/#babel/parser/src/parser/expression.js:1238:16)
at Parser.parseExprSubscripts (node_modules/#babel/parser/src/parser/expression.js:682:23)
at Parser.parseUpdate (node_modules/#babel/parser/src/parser/expression.js:662:21)
at Parser.parseMaybeUnary (node_modules/#babel/parser/src/parser/expression.js:633:23)
at Parser.parseMaybeUnaryOrPrivate (node_modules/#babel/parser/src/parser/expression.js:388:14)
at Parser.parseExprOps (node_modules/#babel/parser/src/parser/expression.js:398:23)
at Parser.parseMaybeConditional (node_modules/#babel/parser/src/parser/expression.js:356:23)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.379 s
Ran all test suites.
Package.json
{
"name": "react-test",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "jest"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"jest": {
"verbose": true,
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleNameMapper": {
"\\.(gif|ttf|eot|svg|png)$": "<rootDir>/test/__mocks__/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
}
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.16.7",
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#types/jest": "^27.4.1",
"#vitejs/plugin-react": "^1.0.7",
"jest": "^27.5.1",
"vite": "^2.8.0"
}
}
App.test.jsx
import React from "react";
import "#testing-library/jest-dom/extend-expect"
import { render } from "#testing-library/react";
import App from "../App.jsx";
test("renders content", ()=>{
const component = render(<App></App>)
console.log(component)
})
The error output is correct, Jest runs on your local node binary and requires that your jsx files be transformed into a syntax it can understand.
Vite does not so this transformation by default. It was designed to transpile and bundle your code into some bundle.js that is appropriate for the browser (it can do other types of output, like libraries. You'd need to tweak your vite.config.js).
Luckily, other folks have solved this problem for you. I'd recommend using vitest, since you wouldn't need to download another transformer or invest a lot of time into setting up tricky build scripts.
Here's a guide on how to quickly set it up:
https://www.eternaldev.com/blog/testing-a-react-application-with-vitest/
And a migration guide:
https://vitest.dev/guide/migration.html
I am trying to integrate vuejs 3 to an existing project which uses webpack. I read about vue-loader, so I am trying to use it.
In the official documentation I have this:
Every time a new version of vue is released, a corresponding version of vue-template-compiler is released together. The compiler's version must be in sync with the base vue package so that vue-loader produces code that is compatible with the runtime. This means every time you upgrade vue in your project, you should upgrade vue-template-compiler to match it as well.
So, when I try to compile I get this error:
Vue packages version mismatch:
- vue#3.0.2 (/home/alejo/playground/parquesFrontend/node_modules/vue/index.js)
- vue-template-compiler#2.6.12 (/home/alejo/playground/parquesFrontend/node_modules/vue-template-compiler/package.json)
This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader#>=10.0, simply update vue-template-compiler.
If you are using vue-loader#<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
But when I try to install vue-template-compiler#3.0.2 I get this error:
❯ npm install vue-template-compiler#3.0.2
npm ERR! code ETARGET
npm ERR! notarget No matching version found for vue-template-compiler#3.0.2.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/alejo/.npm/_logs/2020-11-17T02_52_46_458Z-debug.log
How can I solve this problem?
To make vue 3 work fine with webpack without using vite or vue cli follow these steps :
init the package.json like :
{
"private": true,
"name": "vue-3",
"description": null,
}
install the last version of vue :
npm i --save vue#next vue-loader#next
install also the dev dependencies that includes #vue/compiler-sfc which replaces vue-template-compiler
npm i -D #vue/compiler-sfc css-loader file-loader mini-css-extract-plugin
url-loader webpack webpack-cli webpack-dev-server
#vue/compiler-sfc
css-loader
file-loader
mini-css-extract-plugin
url-loader
vue-loader
webpack
webpack-cli
webpack-dev-server
create or edit your webpack.config.js with following content :
const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env = {}) => ({
mode: env.prod ? "production" : "development",
devtool: env.prod ? "source-map" : "cheap-module-eval-source-map",
entry: [
require.resolve(`webpack-dev-server/client`),
path.resolve(__dirname, "./src/main.js")
].filter(Boolean),
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/"
},
resolve: {
alias: {
// this isn't technically needed, since the default `vue` entry for bundlers
// is a simple `export * from '#vue/runtime-dom`. However having this
// extra re-export somehow causes webpack to always invalidate the module
// on the first HMR update and causes the page to reload.
vue: "#vue/runtime-dom"
}
},
module: {
rules: [
{
test: /\.vue$/,
use: "vue-loader"
},
{
test: /\.png$/,
use: {
loader: "url-loader",
options: { limit: 8192 }
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: { hmr: !env.prod }
},
"css-loader"
]
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css"
})
],
devServer: {
inline: true,
hot: true,
stats: "minimal",
contentBase: __dirname,
overlay: true,
injectClient: false,
disableHostCheck: true
}
});
Add dev script to run your app :
{
"private": true,
"scripts": {
"dev": "webpack-dev-server"
},
"dependencies": {
"vue": "^3.0.2"
},
"name": "vue-3",
"description": null,
"devDependencies": {
...
}
}
Fill the index.html with following content :
<link rel="stylesheet" href="/dist/main.css" />
<div id="app"></div>
<script src="/dist/main.js"></script>
Finally run npm run dev the visit http://localhost:8080/
for a ready to use project try to clone this REPOSITORY which built by following the steps above.
I believe you need to use vue-loader#next with Vue 3
In Vue 3 the SFC compiler package is no longer vue-template-compiler but compiler-sfc (check here)
I completely agree with the suggestion to use Vue CLI to manage the project - it will save you lot of trouble managing all the dependencies (especially now when Vue 3 ecosystem is trying to catch-up with Vue 3 release and lots of tool even don't have any migration documentation ....like vue-loader)
If you are not able to use CLI because your existing project already have Webpack config, you can still use CLI as a guide. Just generate new project on the side, use vue inspect command to inspect Webpack config it is using and package.json for required dependencies...
I've just installed the Webpacker gem in rails that comes with nice tasks that install Vue.
Nevertheless, it installs Vue 2.x with its loader and template compiler...
To bump everything to Vue 3 aand its dependencies simply run:
yarn add vue#next vue-loader#next #vue/compiler-sfc
Voila! You're using Vue 3 now
I upgraded a Vue2 app to Vue3 manually and I was getting this error when I was running the unit tests after upgrading all of the dependencies.
To get everything working, I also had to fix Jest's config file.
In jest.config.js set the "transform" property to:
{
transform: '^.+\\.vue$': `vue-jest`
}
The dependencies I used to get started were from a new Vue3.0 app I created using the cli. Below are the dependencies that my cli settings got me:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-unit-jest": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"#vue/test-utils": "^2.0.0-0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~3.9.3",
"vue-jest": "^5.0.0-0"
}
Note that for my cli settings, the .eslintrc.js also has some minor changes in it for Vue3. In a fresh install the cli makes the "extends" property as below:
extends: [
`plugin:vue/vue3-essential`,
`eslint:recommended`
],
I have an application that is a node backend and a react frontend.
I get the following error when i try to build/run my node application.
Node: v10.13.0
Error:
dist/index.js:314
regeneratorRuntime.mark(function _callee(productId) {
^
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": [ [
"#babel/preset-env", {
"targets": {
"node": "current"
},
}
], "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
webpack.config.js
{
mode: "development",
entry: "./src/index.js",
target: "node",
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: {
colors: true
},
devtool: "source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
sourceMapFilename: "index.js.map"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
}
],
},
node: {
__dirname: false,
__filename: false,
},
"plugins": [
new CleanWebpackPlugin(),
new WebpackShellPlugin({
onBuildStart: [],
onBuildEnd: ["nodemon dist/index.js"]
}),
]
},
package.json
"dependencies": {
"connect": "^3.6.6",
"cors": "^2.8.5",
"dotenv": "^6.1.0",
"express": "^4.16.4",
"hellojs": "^1.17.1",
"i18n-iso-countries": "^3.7.8",
"morgan": "^1.9.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"request": "^2.88.0",
"request-promise-native": "^1.0.5",
"serve-static": "^1.13.2",
"vhost": "^3.0.2"
},
"devDependencies": {
"#babel/cli": "^7.1.5",
"#babel/core": "^7.1.6",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"clean-webpack-plugin": "^1.0.0",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^1.0.1",
"eslint": "^5.9.0",
"eslint-config-google": "^0.10.0",
"eslint-loader": "^2.1.1",
"eslint-plugin-react": "^7.11.1",
"extract-loader": "^3.0.0",
"file-loader": "^2.0.0",
"node-sass": "^4.10.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.26.0",
"webpack-cli": "^3.1.2",
"webpack-node-externals": "^1.7.2",
"webpack-shell-plugin": "^0.5.0"
}
Updated Answer:
If you are using Babel 7.4.0 or newer, then #babel/polyfill has been deprecated. Instead, you will want to use the following at the top of your main js file (likely index.js or similar):
import "core-js/stable";
import "regenerator-runtime/runtime";
Install these packages either with npm:
npm install --save core-js
npm install --save regenerator-runtime
or with yarn:
yarn add core-js
yarn add regenerator-runtime
Original Answer:
I just encountered this problem and came across the following solution:
In package.json I had #babel/polyfill as a dependency. However, in my index.js (My main js file) I had neglected to place the following line at the the top:
import '#babel/polyfill'
Once I imported it, everything worked fine.
I did not need to install babel-runtime as other answers are suggesting.
Babel 7.4.0 and later
There are two main configurations - one for apps and one for libraries.
Option 1: App
When to use: ✔ for applications ✔ global scope polyfills ✔ smallest bundle size ✔ selective inclusion via targets ✔ No need to process node_modules for polyfills
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage", // alternative mode: "entry"
"corejs": 3, // default would be 2
"targets": "> 0.25%, not dead"
// set your own target environment here (see Browserslist)
}
]
]
Install dependencies:
npm i --save-dev #babel/preset-env
npm i regenerator-runtime core-js // run-time dependencies
// regenerator-runtime: transform (async) generators and `async`/`await`
// core-js: other ECMAScript features like Promise, Set, etc.
#babel/preset-env selectively includes polyfills for targets, specified by a Browserslist query. There are two modes - try usage first (more convenient), else entry (more flexible and robust):
useBuiltIns 'usage': no need to import anything manually. All polyfills are added automatically based on their code usage in a file.
useBuiltIns 'entry': Add these import entries once (!) in your app - akin to #babel/polyfill:
import "regenerator-runtime/runtime";
import "core-js/stable"; // or more selective import, like "core-js/es/array"
Extension
For advanced cases, you might use #babel/transform-runtime (dev) and #babel/runtime (run-time) only for Babel helpers to reduce bundle size a bit more - called helper aliasing.
Option 2: Library
When to use: ✔ for libraries ✔ no global scope pollution ✔ includes all polyfills, not selective ✔ bigger bundle size neglectable
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3
}
]
]
Install compile-time and run-time dependencies:
npm i --save-dev #babel/plugin-transform-runtime // only for build phase
npm i #babel/runtime // runtime babel helpers + just regenerator runtime
// OR (choose one!)
npm i #babel/runtime-corejs3
// also contains other JS polyfills (not only regenerator runtime)
// depends on core-js-pure ("ponyfills"/polyfills that don't pollute global scope)
See #babel/plugin-transform-runtime, #babel/runtime, #babel/runtime-corejs.
Extension
You can additionally use #babel/preset-env for syntax transpilation only, with useBuiltIns: false. As the library option does not use global polyfills, you might want to transpile node_modules as well - see the absoluteRuntime option.
Closing notes
Breaking Change: #babel/polyfill is deprecated starting with Babel 7.4.0.
Legacy: If you can't switch to core-js#3, set corejs option to 2 (see migrations). Install #babel/runtime-corejs2 in case of option 2 (#babel/plugin-transform-runtime).
Excellent summary in #9853 by Jovica Markoski
Currently, the library approach doesn't take selective targets into account - meaning you take locally scoped polyfills at the price of bigger bundle size (including all polyfills).
babel-polyfills is a new, experimental approach to inject different polyfills (not just core-js) with different strategies.
This also allows to selectively include locally scoped polyfills.
There is already a very good answer here (originally posted on the Babel6 question) which I will just translate to Yarn. Basically, you need babel runtime (NOT as a dev dependency) and the plugin transform-runtime
yarn add #babel/runtime
yarn add -D #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/transform-runtime"]
}
I had this error in my react project with webpack 4 and this was preventing the whole project to get rendered.
This is how I solved it:
Install plugin-transform-runtime:
npm install #babel/plugin-transform-runtime -D
Add plugin-transform-runtime to the plugin's list in the .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
["#babel/transform-runtime"] // <= Add it here
]
}
For me worked:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
I just solved this error when I imported babel-polyfill directly into the file that shows the error, for example, the error says "ReferenceError: regeneratorRuntime is not defined at /dist/models/usersSchema.js", so I use this in my usersSchema.js file:
require("babel-polyfill");
(you can use import "babel-polyfill";as well)
You will need to have the regeneratorRuntime.
Install this two packages - babel-plugin-transform-regenerator and babel-polyfill
Add the following Babel configuration via .babelrc
{
"plugins": ["transform-regenerator"]
}
React.js Users
If this issue faced you while using react (specifically while trying to use Async/Wait), then Valentino Gagliardi provided a detailed approach on his blog regarding how to address this issue
I need to use lodash-es in my project, but I can't configure my babel correctly, it always reports errors like SyntaxError: Unexpected identifier
hello.js
import upperCase from 'lodash-es/upperCase'
console.log(upperCase('lodash-es'));
package.json
{
"scripts": {
"demo": "babel-node hello"
},
"devDependencies": {
"#babel/cli": "^7.0.0",
"#babel/core": "^7.0.0",
"#babel/node": "^7.0.0",
"#babel/preset-env": "^7.0.0"
},
"dependencies": {
"lodash-es": "4.17.11"
}
}
.babelrc
{
"presets": [
"#babel/preset-env"
]
}
When run babel-node hello, it reports error like:
> /javascript-babel-node-use-lodash-es-issue-demo
> babel-node hello
/Users/freewind/workspace/javascript-babel-node-use-lodash-es-issue-demo/node_modules/lodash-es/upperCase.js:1
(function (exports, require, module, __filename, __dirname) { import createCompounder from './_createCompounder.js';
^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
I've also setup a small demo for this issue, you can clone and try it if you need: https://github.com/freewind-demos/javascript-babel-node-use-lodash-es-issue-demo
Adapted from https://stackoverflow.com/a/31822668/3563013
require("#babel/register")({
ignore: [/node_modules\/(?!lodash-es)/],
});
babel-node by default ignores the node_modules directory. Which is a good thing, else it would be unnecessarily heavy. Packages in node_modules are (at the moment) expected to be in commonjs format. Instead of using lodash-es (es6 format) you should just use lodash (commonjs format). It has exactly the same functionality, the only difference is the format it is written in. More information about that here.
So either tweak babel-node to unignore node-modules/lodash-es (not recommended!) or just install lodash with npm install --save lodash and then rewrite your import like:
import upperCase from 'lodash/upperCase' // instead of lodash-es
console.log(upperCase('lodash-es'));
I am compress my js files by uglify-js
I want to compress Bootstrap 4 js file but it give me Error like this.
Can I compress all js files by only uglify-js Or how can i do it.
Parse error at src\bootstrap\alert.js:1,7
import $ from 'jquery'
^
ERROR: Unexpected token: name ($)
my package.json
"devDependencies": {
"node-sass": "^4.6.1",
"nodemon": "^1.12.1"
},
"dependencies": {
"autoprefixer": "^7.1.6",
"jquery": "^3.2.1",
"postcss-cli": "^4.1.1",
"uglify-js": "^3.1.9"
}
Try using the ES6 version of uglify-js. Replace with this in your package.json
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
or via command line:
npm install --save uglify-js#github:mishoo/UglifyJS2#harmony
uglify-js does not support ES2015 syntax like import statements or arrow functions. Instead, use the uglify-es module:
- "uglify-js": "^3.1.9"
+ "uglify-es": "^3.1.9"