I'm using webpack and babel to transpile my ES6 javascript and React project to a bundle.js.
I'm getting this error:
bundle.js:90058: ERROR - Parse error. Semi-colon expected:
return async function (dispatch) {
Why is the "async" keyword still in the final transpiled bundle.js?
Here is my babel.config.js:
module.exports = {
presets: [
[
"#babel/preset-env",
{
useBuiltIns: "entry",
corejs: 3,
}
],
"#babel/preset-react"
],
plugins: [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-async-to-generator",
"react-hot-loader/babel",
]
};
In my root index.jsx file I have these two imports:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
The actual code in question is the following:
export const getUser = () => async (dispatch) => { ... }
...which gets transpiled to this:
var getUser = function getUser() {
return async function (dispatch) {
...
}
}
Is there some other configuration needed to convert those async/await keywords?
Related
My babel module resolver is not working with React-Native (neither does intellij in VScode)
Here, Is my babel config
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
And jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#assets": ["./assets"],
"#modules": ["./modules"],
"#config": ["./config"],
"#utils": ["./utils"]
}
}
}
I changed import for one of my files and this is the error I get when I executed the build command from Xcode
Error: Error loading assets JSON from Metro. Ensure you've followed
all expo-updates installation steps correctly. Unable to resolve
module ../../modules/store/components/Filters from
src/utils/Router.js:
None of these files exist:
Where I imported the file like this
import Filters from '#modules/store/components/Filters';
I had the same problem, I just removed the '#' from my aliases and it seems working fine now.
Here is my babel.config.js
module.exports = function (api) { ■ File is a CommonJS module; it may be converted to an ES6 module.
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
require.resolve("babel-plugin-module-resolver"),
{
root: ["./src/"],
alias: {
// define aliases to shorten the import paths
components: "./src/components",
containers: "./src/containers",
contexts: "./src/contexts",
interfaces: "./src/interfaces",
organizer: "./src/screens/organizer",
screens: "./src/screens",
},
extensions: [".js", ".jsx", ".tsx", ".ios.js", ".android.js"],
},
],
],
};
};
Try resetting the cache, if above suggested answers don't work
react-native start --reset-cache
This worked for me. For more info see here
Change your module-resolver's root to ['./src/']:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src/'], // <-- here ✅
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
I have a working rollup.config.js file but need to run a separate packaging script after Rollup is done. My plan was to use Rollup's watchers via their JS API. However, I cannot get the JS API to work at all.
I am referencing this code from the Rollup site...
const loadConfigFile = require('rollup/dist/loadConfigFile');
const path = require('path');
const rollup = require('rollup');
loadConfigFile(path.resolve(__dirname, 'rollup.config.js'))
.then(async ({options, warnings}) => {
warnings.flush();
const bundle = await rollup.rollup(options);
await Promise.all(options.output.map(bundle.write));
rollup.watch(options);
})
but I keep getting an error Unknown input options: 0.......Error: You must supply options.input to rollup
My rollup.config.js is as follow...
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from "rollup-plugin-terser";
import replace from '#rollup/plugin-replace';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/bundle.js'
},
plugins: [
json(),
production && replace({
'eruda': ``,
exclude: 'node_modules/**',
delimiters: ['import * as eruda from \'', '\'']
}),
production && replace({
'eruda': ``,
exclude: 'node_modules/**',
delimiters: ['', '.init()']
}),
svelte({
dev: !production,
css: css => {
css.write('public/bundle.css');
}
}),
resolve({ browser: true }),
commonjs(),
!production && livereload('public'),
production && terser()
],
watch: {
clearScreen: false
}
};
Any thoughts are appreciated!
I think the example at rollupjs.org is wrong. Shouldn't it be like this instead?
const loadConfigFile = require('rollup/dist/loadConfigFile')
const path = require('path')
const rollup = require('rollup')
// load the config file next to the current script;
// the provided config object has the same effect as passing "--format es"
// on the command line and will override the format of all outputs
loadConfigFile(path.resolve(__dirname, 'rollup.config.js'), {format: 'es'})
.then(({options, warnings}) => {
// "warnings" wraps the default `onwarn` handler passed by the CLI.
// This prints all warnings up to this point:
console.log(`We currently have ${warnings.count} warnings`)
// This prints all deferred warnings
warnings.flush()
// options is an "inputOptions" object with an additional "output"
// property that contains an array of "outputOptions".
// The following will generate all outputs and write them to disk the same
// way the CLI does it:
options.map(async options => {
const bundle = await rollup.rollup(options)
await Promise.all(options.output.map(bundle.write))
// You can also pass this directly to "rollup.watch"
rollup.watch(options)
})
})
Figured it out, apparently the options returned from loadConfigFile is an array so I had to do options[0] inside the async function
Following simple code:
const { exec, spawn, fork, execFile } = require('child_process')
const startAllJobs = async () => {
const process = fork('app/util/nlp/sentenceHelper.js');
};
sentenceHelper:
import { split } from 'sentence-splitter';
/*....more but unimportant since it breaks at first line*/
Babel setup:
starter.js
// Transpile all code following this line with babel and use 'env' (aka ES6) preset.
require("#babel/register")({
extensions: ['.js', '.ts'],
"presets": [["#babel/preset-env"
], "#babel/preset-typescript"],
"plugins": ["#babel/plugin-transform-runtime"]
})
require("#babel/polyfill");
require('datejs');
// Import the rest of our application.
module.exports = require('./app/index.js');
Error:
import { split } from 'sentence-splitter';
^
SyntaxError: Unexpected token {
How can I use ES6 Syntax within child processes?
Node version: 12.0.0
How can I mock an ES6 module import using Jest?
For example we have the following structure:
// ../store.js
function getData(data) {
return data / 3;
}
export { getData };
// ../myModule.js
import { getData } from './store';
function myModule(param) {
return getData(param) * 4;
}
export { myModule };
// ./myModule.test.js
import { myModule ] from '../myModule';
test('2 x 4 equal 8', () => {
expect(getData(6)).toBe(8);
});
To mock ES2015 modules, your jest config needs to use babel to convert the modules first.
You'll want to yarn add --dev babel-jest babel-preset-env
and then your package.json should look something like this:
"jest": {
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$",
"^.+\\.module\\.css$"
]
}
Secondly, in your .babelrc you need to specify your environment for test like so:
{
"presets": [
["env", "react"]
],
"env": {
"development": {
"presets": [["env"], "react"]
},
"production": {
"presets": [["env"], "react"]
},
"test": {
"presets": [["env"], "react"]
}
}
}
Once that's done, you can mock a module. For example, make a file called __mocks__/store.js (where the mocks folder is in the same level as your store.js file. Inside of your mocks file, you can do something like
const getData = () => return 42;
export { getData };
and in your myModule.test.js you need this line:
jest.mock('./store');
If you want, you can see a working example from one of my repositories here:
https://github.com/AnilRedshift/linkedINonymous/
If you want make automated test with jest, you have to include before the test/describe the next call
jest.mock('../myModule');
It returns void result from all functions.
Other alternative is mock mixed:
const mock: any = jest.genMockFromModule('../myModule');
mock.getData = jest.fn().mockImplementation(6);
The call to method getData returns 6.
I am using rollup to build my library and I have a dependency on lodash.
but when I run rollup to bundle my code, I get this warning.
(!) Unused external imports
reduce imported from external module 'lodash' but never used
A sample of my code is as follow:
import { reduce } from "lodash"
export function someutilityfunction(args) {
return reduce(args,() => {
// do somthing
}, {}) // A generic use case of reduce function
}
the bundled library works fine.
I have even tried using
import * as _ from "lodash"
and lodash-es instead of lodash
but no success.
Here is my rollup.config.js
import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import filesize from 'rollup-plugin-filesize'
import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import uglify from 'rollup-plugin-uglify'
let production = (process.env.NODE_ENV == "production")
export default {
input: 'src/index.ts',
output: {
file: 'lib/index.js',
format: 'cjs',
name: 'my-library',
sourcemap: true
},
external: [
'rxjs',
'axios',
'lodash'
],
plugins: [
resolve(),
typescript({
tsconfigOverride: {
compilerOptions: {
declaration: true,
moduleResolution: "node",
allowSyntheticDefaultImports: true
}
},
// verbosity: 3,
clean: true,
rollupCommonJSResolveHack: true,
abortOnError: false,
typescript: require('typescript'),
}),
commonjs(),
babel({
exclude: 'node_modules/**'
}),
production && uglify(),
filesize()
],
watch: {
include: 'src/**'
}
};
I have used this rollup config before and it has worked fine, until now.
Am I missing something?
And I know the title of the question can be more generic. feel free to improve the post.
Looks like there is a known issue with the tree-shaking within Rollup and Lodash (also D3 has a similar problem):
https://github.com/rollup/rollup/issues/691