Transpiling React code, but leave ES6 alone - reactjs

I'm writing a Chrome Extension using ES6/React/Redux babel and Gulp.
I was using babel presets es2015, stage-2 and react.
Then I realized as I'm only targeting Chrome I could get rid of the es2015/estage-2 stage as it's supported by Chrome.
So the first I tried was to get the .babelrc and remove the references to es2015 and stage-2.
Not so fast... Before running webpack gulp script fails to run.
What I tried first was to make only the gulp file ES5 compatible.
Then I got errors of spread operators not being supported, so I re-added "stage-2" loader.
Then I got errors in different modules:
> WARNING in ./background/src/index.html Module parse failed:
> /my_path/my_project/src/index.html Unexpected token (1:0) You may need
> an appropriate loader to handle this file type. SyntaxError:
> Unexpected token (1:0)
> at Parser.pp$4.raise (/my_path/my_project/node_modules/acorn/dist/acorn.js:2221:15)
To help to understand how my code is structured, it's in 3 main folders:
background, content and popup. Each one representing a Chrome environment.
For each one, I have a separated webpack.config.js file, similar to this one: https://pastebin.com/hseVyQaw
Gulp then calls webpack for each config file and generated the bundle output file for each one, during the build process.
There's a way to make Gulp/Webpack works with ES6 syntax, while not transpiling it for the deployment?
What's the best approach for this issue?
Gulp version
> [17:32:27] Requiring external module babel-register
> [17:32:27]CLI version 3.9.1
> [17:32:27] Local version 3.9.1
Webpack version: 1.14.0
UPDATE
After adding html-loader as suggested by #Michael Jungo it seems to run fine, but it gives me a warning, not sure how bad is to ignore it:
WARNING in ./background/src/index.js
Critical dependencies:
17:29-52 the request of a dependency is an expression
# ./background/src/index.js 17:29-52
UPDATE 2
Oh, Chrome is complaining about modules syntax of my extension, but based on what I read it's suppose to be supported:
Uncaught SyntaxError: Unexpected token import

Your error is not related to babel or any ES6 features. You're trying to import the HTML file ./background/src/index.html but in the config you've posted, there is no rule for .html that could handle these files, therefore webpack tells you that you might need an appropriate loader for this file type.
You can use the html-loader and add the following rule to your loaders array:
{
test: /\.html$/,
loader: 'html-loader'
}
As for your babel config, it should work as you wanted. Keep in mind if you're using ES modules (import/export) you would still need to transpile them or switch to webpack 2 which supports them out of the box. Also UglifyJs doesn't understand ES6 syntax, if you want to uglify ES6 you have to use an alternative like babili with the babili-webpack-plugin.

Related

You may need an additional loader to handle the result of these loaders error with CRA

I installed a package called "dids", which I believe contains another package "did-jwt" that is causing this error:
Module parse failed: Unexpected token (192:53)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| return t.find(e => {
| const r = p(I(e));
> return r === i || r === c || e.ethereumAddress?.toLowerCase() === u || e.blockchainAccountId?.split("#eip155")?.[0].toLowerCase() === u;
| });
| }).filter(e => null != e);
I started looking into webpack, babel, and what goes on behind CRA, since I saw the error was with loaders, babel, and webpack. I'd never looked into the toolchain before since I've only been using React for a bit. I have a better understanding of the problem, but am still confused why its happening, and how to solve it? I looked into running npm run eject but only wish to use that as a last resort.
My current understanding is that webpack compiles and bundles the JS code, and Babel transpiles the code to transform more modern JS into older JS so its understandable by older browsers. (feel free to correct me on this, my understanding still rusty). Webpack uses loaders while bundling and calls upon loaders to do certain thing, like babel to transpile. But in this case, why can babel not compile this piece of code?
I also saw this post: "You may need an additional loader to handle the result of these loaders."
Which explains that babel doesn't run on dependencies in the project, only the source code. But it seems that babel lis running on the did-jwt dependency?
Dor your very special case (did-jwt) you might be able to use an older release of did-jwt (just made it work on my machine with v5.1.0 for example). When did-jwt is a transitive dependency and you're using yarn, you could put this in your package.json:
"resolutions": {
"did-jwt": "5.1.0"
},

Test suite fails to run because of an error in pure.js using react-testing-library/react-hooks

I am testing a react app with the react-testing-library. To use renderhooks, I had to add the '#testing-library/react-hooks' library. This library depends on another library "pure.js". Running tests that makes use of renderhooks in vscode works fine but shows and error in a web IDE.
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
/projects/challenge/node_modules/#testing-library/react-hooks/lib/pure.js:41
} catch {
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (node_modules/#testing-library/react-hooks/lib/index.js:11:13)
How do one get around this error?
The try/catch is a modern JavaScript feature and supported since Node version 10.
Try to update Node.js if your version is < 10
Please also see this answer here: https://stackoverflow.com/a/62971606/1108161
Ok, so look at the documentation here.
Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to allow transpiling such modules. You'll find a good example of this use case in React Native Guide.
Your error message states that Jest has found code it can't understand, and is suggesting that you transform it. It also says that the code it can't understand is in node_modules/#testing-library.
However, the default value for transformIgnorePatterns is ["/node_modules/", "\\.pnp\\.[^\\\/]+$"], which means that the node_modules folder will not be transformed. To allow jest to transform the folder, you need to change the transformIgnorePatternsvalue to something else that includes the file Jest can't understand. That could e.g be something like
"transformIgnorePatterns": [
"node_modules/(?!(#testing-library)/)"
]

can't find less loader and rules in webpack.conf

I want to add Less support to a React project. According to these links:
Adding SASS or LESS support to create-react-app
React + CSS Modules + LESS + Webpack 4
I ejected project and installed less and less-loader, but I can't find rules section in webpack.config.js.
Why my config file is not like the config file in these two pages? (webpack version is 4.1.0)
How can I add Less support to my project?
If I add
{
loader: require.resolve('less-loader'),
},
to file config, I'll get "Failed to compile" error
Cannot read property 'denominator' of undefined
in ...\node_modules\bootstrap\dist\css\bootstrap.css (line 2100, column 2)
Those tutorials are based on the old CRA, in the latest one they merged dev and prod files and did some additional mumbo jumbo to make it more "concise". One of those things was extracting CSS loaders into a standalone helper function - getStyleLoaders(). The rules section is below and the output of getStyleLoaders is merged onto it at an appropriate point.
In general what you are doing by appending your loader at the end of loaders array, is correct. And the error is not on the webpack side. It's rather thrown by less-loader not being able to interpret the file, because of invalid syntax inside.

React Photoswipe using removed babel 5 option

I am just starting to dabble in react and one of the first components I want is something to use photoswipe.js. (react photoswipe) It looks like there is a pretty decent one on npm, but I am running into a problem. When I run my storybook to start testing and building my component, I get an error from babel. It says:
in ./~/react-photoswipe/lib/index.js
Module build failed: ReferenceError: [BABEL] C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\lib\index.js: Using removed Babel 5 option: C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
at Logger.error (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
at OptionManager.mergeOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
at OptionManager.init (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
at File.initOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:212:65)
at new File (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:135:24)
at Pipeline.transform (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
at transpile (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\index.js:46:20)
at C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:79:18
at ReadFileContext.callback (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:15:14)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)
So I did a bit of poking around and noticed that the babel rc file appears to be set to stage:0 which from my understanding seems like a really bad idea if you are producing a component that is supposed to be durable as the javascript spec updates and evolves.
I am still pretty new to using babel though so I am kind of having a hard time tracking down what I would need to update for this component to get it working in my environment with the newer babel. Has anyone encountered this problem with this component before? Does anyone have any advice or tips on how to troubleshoot the bable transpile and track down what I need to update?
The .babelrc from react-photoswipe does not work with babel 6. But it doesn't need to, because main entry point of the module is lib/index.js, which contains the already transpiled code. You're trying to transpile it again, and it automatically applies the .babelrc closest to it.
You should exclude node_modules in your webpack config, for example:
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
It will not only fix your issue, but also reduce the build time.
Thanks Michael for getting me pointed in the right direction. I am testing and building a component using a react storybook tool that has a whitelist configuration that tells it what node modules not to run through the full build. I had to add react-photoswipe to that whitelist and it is now working... well starting to work, but this problem is taken care of.

Webpack + Angular2 AOT: Uncaught SyntaxError: Unexpected token import

in this set-up, how do you transpile the angular2 library being imported from the generated ngfactory files?
the current app is a combination of the webpack + aot cookbook based on the angular docs
angular.io/docs/ts/latest/cookbook/aot-compiler.html
angular.io/docs/ts/latest/guide/webpack.html
I have a working POC where you can replicate the issue from this repo:
https://github.com/jetlogs/Angular2-AOT-Localization
after you've done the compilation / bundling, you can open the 2 files:
non-aot.html - this is the non-aot version of the same app, and it loads fine
aot.html - this file fails with:
ng_module_factory.js?95b1:13 Uncaught SyntaxError: Unexpected token import
Expected behavior
the expected behavior is that aot.html and non-aot.html should have the same behavior
Minimal reproduction of the problem with instructions
clone the repo, then
run these commands on the working directory:
npm install
npm postinstall
npm run build
then open aot.html to reproduce the issue
Is there any way on how to fix the import statements from the imported angular2 libraries? Thanks
UPDATE:
I've tried transpiling the angular2 source files which are in ES2015 by using the babel-loader:
{
test: /\.js$/,
loader: 'babel',
include: [
/node_modules(\\|\/)#angular/
],
exclude: [
/\.umd\.js$/
],
query: {
presets: ['es2015']
}
},
it now compiles without issues with ES6 incompatibilities, however, it now encounters a new error only for aot.html:
core.umd.js?e2a5:3272Uncaught Error: No provider for NgZone!
any reason why transpiled angular2 source codes being referenced by the AOT compiler are cdausing NgZone issues?
I've updated the repo above to reflect my latest changes
UPDATE2: 10/13/16
Updated to Angular 2.1
still the same issue
The System.import syntax used in ng_module_factory.js is ES6 style module loading. Webpack 1, which you are probably using, does not support this syntax.
A workaround might be to transpile the Angular ES6 modules to ES5 with require() syntax, but you already tried this without success.
However you might consider switching to Webpack 2, which fully supports ES6 style imports and is very close to its stable release. The compilation worked for me this way without changing anything except for the webpack config which uses a new syntax for some parts.
For me it was a wrong import generated by IDE:
import { Component, Output } from "#angular/core/src/metadata/directives";
Instead of:
import { Component, Output } from "#angular/core";

Resources