Webpack cant compile ts 3.7 (Optional Chaining, Nullish Coalescing)

TypescriptWebpackTs Loader

Typescript Problem Overview


I try to use typescript 3.7 features like Optional Chaining, Nullish Coalescing. But webpack gives me an error while transpaling.

app: Module parse failed: Unexpected token (50:40)
app: File was processed with these loaders:
app:  * ../../../node_modules/ts-loader/index.js
app: You may need an additional loader to handle the result of these loaders.
app: | export const Layout = (props) => {
app: |     const regionsResults = useQuery(regionsQuery, { fetchPolicy: 'cache-first' });
app: >     const regions = regionsResults.data?.regions ?? [];
app: |     const userItem = useQuery(usersProfileQuery, { fetchPolicy: 'cache-first' });
app: |     const handleOnClick = (selected) => props.history.push(selected.key);
``

Typescript Solutions


Solution 1 - Typescript

I changed target: esnext to es2018 in tsconfig.json file. Now it works.

Webpack issue for reference : https://github.com/webpack/webpack/issues/10227

Solution 2 - Typescript

Depending on which loader you're using to transiple the code, there are several options available

For ts-loader, you need to make sure the output from typescript is understandable by Webpack. This can be achieved by setting target to ES2018 in tsconfig.json.

For babel-loader, you'll need to make sure babel loads the

  • @babel/plugin-proposal-nullish-coalescing-operator
  • @babel/plugin-proposal-optional-chaining

plugins. Note that if you're using preset-env, it may or may not load these plugins depending on your targets or browserlist (ie, won't be loaded if the target env has support for these language features), in which case the only way to guarantee their inclusion is by manually specifying them in the plugins array in babel.config.js,

  plugins: [
    '@babel/plugin-proposal-nullish-coalescing-operator',
    '@babel/plugin-proposal-optional-chaining',
  ],

Solution 3 - Typescript

If you're using vs code, probably you should change the local typescript version vs code use.

https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdgaras KarkaView Question on Stackoverflow
Solution 1 - TypescriptEdgaras KarkaView Answer on Stackoverflow
Solution 2 - TypescriptaryzingView Answer on Stackoverflow
Solution 3 - TypescriptAlex HyriavetsView Answer on Stackoverflow