Babel 7 Unexpected token for React component - javascript

I'm upgrading to Babel v7 from v6 and when I build the project I get the following error:
Syntax error: src\app\layout\components\FooterToolbar.js: Unexpected token
I'm using the following .babelrc configuration
{
"presets": [
["#babel/preset-env", { "useBuiltIns": "usage", "debug": true }],
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
And finally this is my webpack config. I put the pollyfills first and then the index.js file in the entry and the babel-loader as transpiler
entry: ["#babel/polyfill", paths.appIndexJs],
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{ loader: 'babel-loader' }],
},
Any advice to solve this issue? Thanks a lot
EDIT: I'm using typescript in this project. This is the tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"isolatedModules": true,
"strict": true,
"noEmit": true,
"allowJs": true,
"resolveJsonModule": true,
"jsx": "react"
},
"include": [
"src"
]
}

Finally got it to work by updating webpack, its plugins and adding the presets and plugins inside the webpack configuration
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{
loader: 'babel-loader',
options: {
presets: [
["#babel/preset-env", { modules: "commonjs" }],
"#babel/preset-typescript",
"#babel/preset-react"
],
plugins: [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
}],
},
Thanks for your answers, hopefully this is useful for someone else

Related

`Cannot read properties of undefined` for enum after bundling with webpack

I have a React Library that I want to make buildable using Webpack. The library is written using Typescript. It seems everything is working, but for some reason enums aren't.
When I install the library into my React App, I find Cannot read properties of undefined in the browser console for the enum.
I've tried looking in the outputted bundle and it does appear that the enum is being compiled into the bundle. I feel like I must have a misconfiguration somewhere. Before I was able to bundle with microbundle-crl which we're moving from in favour of Webpack.
Here is my webpack.config.js file:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const DtsBundleWebpack = require('dts-bundle-webpack');
module.exports = {
mode: 'production',
entry: './src/index.tsx',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
resolve: {
extensions: ['.tsx', '.ts', '.json', 'jsx', '.js'],
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader, //Extract css into files
'css-loader', // Turns css into commonjs
],
},
{
test: /\.pcss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader', // Turns css into commonjs
'postcss-loader'
]
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: 'randomcompany-components.css' }),
new DtsBundleWebpack({
name: '#randomcompany/components',
main: './dist/src/index.d.ts',
out: '../index.d.ts',
}),
],
};
My tsconfig.json is as follows:
{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"lib": ["dom", "esnext"],
"types": ["react", "react-scripts"],
"moduleResolution": "node",
"jsx": "react",
"sourceMap": true,
"declaration": true,
"declarationDir": "dist",
"esModuleInterop": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"isolatedModules": true,
"preserveConstEnums": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
},
"include": ["src", "src/lang"],
"exclude": ["node_modules", "dist", "src/stories"]
}
My enum is in this format:
export enum Test {
TestOne = "Test One",
TestTwo = "Test Two",
TestThree = "Test Three"
};
export default Test;
You should write it like below:
const Test = {
TestOne: "Test One",
TestTwo: "Test Two",
TestThree: "Test Three",
};
export default Test;
But in my opinion, using enum makes your bundle file a little bit heavy, just advise. use simple JavaScript objects.

Absolute Imports not working with WebPack

I'm trying to setup up absolute imports, but it seems my webpack configs are wrong and the entry point it starts from is relative and not from ./src
I've looked through the webpack docs and they recommend adding an entry point, which I have but still nothing.
Error I get:
Module not found: Error: Can't resolve 'contexts' in '/Users/gurneet/Desktop/Projects/projectfrontend/src/components/Home'
structure:
Project
|- src
| - components
| - Home
| - Featured.tsx
| - contexts
| - index.ts
| - AllDataProvider.tsx
|-package.json
|-tsconfig.json
|-webpack.config.js
// FEATURED.TSX
import React from 'react';
import {useData} from '../../contexts'; // this works
import {useData} from 'contexts'; // this doesn't work.
Even though when I hover over both the imports they points to the say index.ts file that has all the exports.
// WEBPACK
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
devServer: {
historyApiFallback: true,
},
entry: './src',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {
// make all svg images to work in IE
iesafe: true,
},
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'public/_redirects' },
],
}),
],
};
//TSCONFIG
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"baseUrl": "src",
"paths": {
"src/*": ["src/*"]
},
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
Where am i going wrong?

ts-loader not working (You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file)

I'm trying to add TS to a JS project and it doesn't seem like webpack is picking up ts-loader for .tsx files. I've tried using babel and awesome-ts-loader and nothing that other people have done seem to work.
Full error:
ERROR in ./src/components/Account/Test.tsx 3:0 Module parse failed:
The keyword 'interface' is reserved (3:0) You may need an appropriate
loader to handle this file type, currently, no loaders are configured
to process this file. See https://webpack.js.org/concepts#loaders
webpack config
const includePaths = [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'test'),
path.resolve(__dirname, 'package.json'),
];
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
},
],
include: includePaths,
},
{
test: /\.jsx?$/,
use: {
loader: 'babel-loader',
},
include: includePaths,
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
query: moduleStyle,
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader',
},
],
include: includePaths,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader'],
include: includePaths,
},
{
test: /\.(gif|png|jpg|eot|woff|ttf|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'web/[hash].[ext]',
},
},
],
include: includePaths,
},
],
},
tsconfig
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"sourceMap": true,
"module": "ES2015",
"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"app/*": ["src/*"]
},
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "react"
},
"include": ["src"]
}
Test component that I'm trying to import in JS file
import React from 'react';
interface TestComponentProps {
prop1: string;
prop2: string;
}
const TestComponent: React.FC<TestComponentProps> = ({ prop1, prop2 }) => {
return (
<div>
Test Component
<div>{prop1}</div>
<div>{prop2}</div>
</div>
);
};
export default TestComponent;
Just change path to source folders:
const includePaths = [
path.resolve(__dirname, '../src'),
path.resolve(__dirname, '../test'),
path.resolve(__dirname, '../package.json'),
];
I had a similar issue after I decided to move webpack config into a config folder.
I assume that your folder structure might be:
-config/
|_webpack.config.js
-src/
|_/components/
|_index.ts
tsconfig.json
package.json
Just adjust values in includePaths variable depending on your folder structure.

Uncaught ReferenceError: exports is not defined after Webpack Code Split

I am trying to optimize my webpack bundle size by splitting it into two bundles: webpack-bundle.js, which contains my code, and vendor-bundle.js, which contains node modules and third party libraries. But after I successfully created two bundles, I am getting two errors in the browser regarding both bundles:
Uncaught ReferenceError: exports is not defined at vendor-bundle.self-879f615019647c756dc959f99d735b3a2534b00805364ae6fca0091d1190d62d.js?body=1:1
Uncaught TypeError: Cannot read property 'call' of undefined at I (webpack-bundle.self-78221fc03008c178fe970b69731594f14d651dab84e5cf928beacc805ebde79c.js?body=1:1)
This is my webpack.config.js.
const config = {
"entry": {
"webpack-bundle": "./app/registration",
},
"output": {
filename: "[name].js",
path: pathLib.resolve(__dirname, "../app/assets/webpack"),
},
"module": {
"rules": [
{
"exclude": /node_modules/,
"test": /\.jsx?$/,
"use": {
"loader": "babel-loader",
"options": {
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
}
}
],
},
"plugins": [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
}),
new UglifyJsPlugin(),
],
"optimization": {
"splitChunks": {
"cacheGroups": {
"vendor": {
"test": /node_modules/,
"chunks": "all",
"name": "vendor-bundle"
}
}
}
},
"resolve": {
"alias": {
"Lib": pathLib.resolve(__dirname, "app/lib/"),
"Shared": pathLib.resolve(__dirname, "app/shared/")
},
"extensions": [".js", ".jsx"]
},
"target": "node"
};
module.exports = config;
This is my .babelrc:
{
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
We use React, Rails, React on Rails, and Slim. To load webpack, I'd add this to my application.slim:
= javascript_include_tag 'vendor-bundle'
= javascript_include_tag 'webpack-bundle'
I want to be able to serve the two bundles I created. Is there anything wrong in the way I configured my webpack and split the bundle? Or should I install something else?
At the bottom of your webpack config, you have your target mode set to node
In node, module and module.exports both exist, but these don’t exist in the browser - this is what’s causing the error
If you remove this line, webpack will assume you’re targeting browsers instead, and will also transform this line for you - your bundles should then run in the browser as expected.

"Unexpected token import" angular 2 external module

I'm using the ngx-magicsearch module in my project with. However, I get the following error:
Uncaught SyntaxError: Unexpected token import.
I am using the version of Angular 4.2.5, Webpack version 1.15.0 and Typescript 2.3.4
Here is my Webpack file:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'app': './app/app.module.ts',
'vendor': './app/vendor/vendor.ts'
},
resolve: {
extensions: ['', '.ts', '.js', '.css', '.html'],
modulesDirectories: ["node_modules", "assets\\js"]
},
output: {
filename: '[name].bundle.js',
},
module: {
noParse: [/jszip.js$/],
loaders: [{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-router-loader'
]
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?.*$|$)/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: './app',
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: './app',
loader: 'raw'
},
{
test: /[\\\/]assets[\\\/]js[\\\/]modernizr\.min\.js$/,
loader: "imports?this=>window!exports?window.Modernizr"
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
KJUR: "jsrsasign-latest-all-min",
b64utoutf8: "base64x",
dateFormat: "dateformat",
moment: "moment"
}),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor']
})
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
};
tsconfig.js:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"sourceMap": true,
"preserveConstEnums": true,
"alwaysStrict": true
},
"exclude": [
"node_modules"
],
"compileOnSave": false,
"buildOnSave": false
}
And the errors:
The entry point of ngx-magicsearch uses ES modules. You would need to transpile them with babel to use it. Usually the packages publish a transpiled version, although many of them now also publish a version with ES modules that can be used by bundling tools that support them. ES modules are supported out of the box, since webpack 2.
It is highly recommended to upgrade webpack. You'll have to adapt your config a little. For details have a look at the official migration guide.

Categories

Resources