Error: Should not import the named export 'version' (imported as 'version')
Asked Answered
B

13

103

I have an ejected create-react-app project. I am getting this error after updating it to webpack 5. It was working fine with webpack v4.41.5

OS: MacOS Catalina 10.15.7
node: v10.23.0

Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon).

Bugbane answered 24/11, 2020 at 18:58 Comment(7)
Did you find a solution?Eraste
yes. The error was because of the following line in the code. const packageJson = require('../package.json').Bugbane
Solution here #70299448Romaromagna
Here's another option #41124131Salomo
@karel I am writing this comment in response to your edit. The webpack config is not useful to the question. The only thing that matters is the upgrade to webpack 5 form webpack 4.Bugbane
I removed the webpack config.Efren
I see a lot of users doing the complete import and then destructuring it later. The question still remains though why import {abc} from "some.json" warns me when abc attribute exists in json?Dexter
A
162

Change the following

import { version } from '../../package.json';

to something like

import packageInfo from '../../package.json';

And then change your access from something like

version,

or

version: version,

to

version: packageInfo.version,

As noted in the comments, there may be cases where you do not want to expose your entire package.json file in the client code.

Azoth answered 22/4, 2021 at 15:53 Comment(10)
But doesn't this pose a security risk and expose the entire package.json to the client?Accusatorial
That question seems unrelated to the question above. My answer simply addresses the question, not whether it is a good practice or secure in all contexts. If you have private/secret contents in your package.json and don't want them to ever be available in your JS code, then don't do this. How to do this in a more secure way should be covered in a separate question.Azoth
import * as packageInfo from '../../package.json'; version: packageInfo.version,Retrorocket
@Azoth even without secrets in the package.json I find this extremely unsecure. Most devs and maintainers, even with experience, will not treat the package.json as something in the public domain. And with an implementation like that 'hidden' in the codebase really painful shots in the foot lie ahead. Especially so since this error now comes up for Angular 12 which is client-side technology. So a clearly visible HEADS-UP would be fitting imho.Soosoochow
Agree with @JeyDWork, this solution should be flagged as potential security risk. If your package.json doesn't contain confidential data now, who will guarantee that other developers won't put it there years later, without knowing that it is exposed to production? And even without any secrets, normally, a business doesn't want to expose information about its dependencies and devDependencies from the package.json to everybody - it makes it easier to find vulnerabilities and penetrate the application.Headforemost
Follow-up question on how to do this securely here: #70299448Bonnee
This does not fix the issue, you will now get this Warning instead. Should not import the named export 'version' (imported as 'packageJson') from default-exporting module (only default export is available soon)Edea
Update the import statement as import packageInfo from '../../package.json'; @EdeaMetaphrast
how to handle if need to import multiple packageinfo from different packages?Sadowski
Guys I think Answer from Nihar H Rupareliya might be the best option for this. Could you check if there could be anything wrong with it? https://mcmap.net/q/112195/-error-should-not-import-the-named-export-39-version-39-imported-as-39-version-39Rockafellow
G
40

You should also add "allowSyntheticDefaultImports": true, to the compileroptions in the tsconfig.json

Gennygeno answered 15/5, 2021 at 13:6 Comment(4)
tried on Angular v12 (after upgrading from v9). Did not work in my case. tried to add both to tsconfig.json and tsconfig.app.jsonKirst
@NuryagdyMustapayev this worked for me: import * as packageInfo from '../../package.json'; and rename the variable instead of accesing version directly someName = packageInfoPseudo
maybe you also have to add "resolveJsonModule": true, "esModuleInterop": true to your tsconfig.json to be able to apply default import for jsonNeedless
may be worth to take a look at #49996956Needless
C
33

I solved my issue with the following:

    import packageInfo from './package.json';
    
    
    version = packageInfo.version;
Couscous answered 24/1, 2022 at 12:58 Comment(3)
This syntax is the correct syntax to useOrthopterous
This together with "resolveJsonModule": true, "allowSyntheticDefaultImports": trueRealize
Why does this doesn't expose something in comparison to { key } import?Spode
N
17

How about const appVersion = require('./package.json').version; ?

Using this we are not actually shipping the whole package.json but just bringing in the version from it.

Nestle answered 12/1, 2022 at 22:26 Comment(2)
I imported JSON files in the unit testing codes in my Angular project. I started getting this error after upgrading the Angular version to v12. In my test code, I already was importing in the correct way as described in the accepted answer, but I was getting this error. Changing to require is solved for me. thanks.Kirst
Best answer, 1 line of code.Sindee
S
9

With latest version of create react app, following syntax works:

import rData from './registration-form.json';
Structuralism answered 29/12, 2021 at 6:38 Comment(0)
C
6

This is how I have solved the issue (the rest of the answers didn't work for me). Solution found from here https://www.angularfix.com/2021/10/error-should-not-import-named-export.html

Step 1

add the following to your ts.config file

"resolveJsonModule": true,
"esModuleInterop": true,

(add them at the end of your "compileroptions" block)

  "compilerOptions": {
    // 
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true
  },

Step 2

Import the file you want using the following syntax. Of course change the name of the file to your file name.

import {default as data} from '../../package.json';

Step 3

You can now access your variables via this syntax

data.variable_name

This is basically what my file looks like, it compiles successfully

import {default as authInfo} from '../../auth_config.json';

export const environment = {
  // 
  domain: authInfo.domain,
  clientId: authInfo.clientId
};
Cadaver answered 15/6, 2022 at 14:29 Comment(1)
This solution helped me, and it's precisely what I needed because I'm in the middle of authentication configuration too :)Germayne
H
4

For Angular 12 +, Follow this steps:

Step 1: We need to use the require node function in our environment files, so we have to add node types to the compiler options. Open tsconfig.app.json and tsconfig.spec.json files (usually they are located under the ‘src’ folder), add “node” under compilerOptions -> types

...
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "types": [
      "jasmine",
      "node"
    ]
  }
...

Note: Be sure to have included ‘@type/node’ as a dependency in your ‘package.json’ file.

Step 2: Now open environment.ts (‘src\environments\environment.ts’) and create a property for holding the application version in environment variable as follows ( in our case this will be appVersion) :

export const environment = {
  appVersion: require('../../package.json').version + '-dev',
  production: false
};

Be aware, the path to package.json must be calculated from the environment file’s location.

The require(‘../../package.json’).version will load the version number from the package.json file and + ‘-dev’ will add the ‘-dev’ suffix to it. The suffix isn’t a must, but this way you can identify witch environment file is used for running your application

Following the same approach we have to edit the production environment file as well. In the end the environment.prod.ts will look like this:

export const environment = {
    appVersion: require('../../package.json').version,
    production: true
};

Step 3: Add version number to a component and show it in the application. For example:

import {Component} from '@angular/core';
import {environment} from '../environments/environment';

@Component({
    selector: 'app-root',
    template: `<h1>{{title}}</h1>
    <h3>v{{currentApplicationVersion}}</h3>`
})
export class AppComponent {
    title = 'Demo application for version numbering';
    currentApplicationVersion = environment.appVersion;
}
Hootman answered 26/5, 2022 at 7:58 Comment(0)
L
3

I had the same error then I realize that the issue was because I used

import {logo} from '../assets/logo.png';

Instead of

import logo from '../assets/logo.png';

The curly braces are only used for import when export is named. For a default export (a file which isn't being exported from another) we do not use { } when we import

Lindeberg answered 24/7, 2023 at 13:1 Comment(0)
I
0

Just for further reference this does not happen with just the package.json I had the same problem with packages from the @atlaskit after an update to webpack v5 and found good explanation and fix there:

You can import JSON files directly into Javascript files. This is supported by node and by Webpack. In older versions of Webpack you could import either the default export which represents the whole JSON blob or a named export for each top level property in the JSON file.

As of Webpack 5 the named export is deprecated which mirrors the behaviour of node.

To work around use in webpack config:

ignoreWarnings: [
/only default export is available soon/,
],
Idalia answered 4/4, 2022 at 15:32 Comment(1)
Ok as a temporary solution, but not good in long term because Webpack threatens to remove the named export support.Borman
D
0

This is too late but I am adding it because it will help some others. first you have to import the file like import bglogo from "../data/data.json" then create a variable const logo=bglogo.logo; the use it as logo

Dihydric answered 17/3, 2023 at 13:2 Comment(0)
M
0

i had the same error and i fixed it by deleting the curly braces {} when importing Logo.png photo ..

Milton answered 27/4, 2023 at 17:16 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Shurwood
T
0

None of these worked with Angular 16. Here is what did work for me.

  1. "compilerOptions": {
      // 
      "resolveJsonModule": true,
      "allowSyntheticDefaultImports": true
    },
    
  2. import * as packageInfo from '../../package.json';
    

    Note: If you try to reference packageInfo.version (or any other attribute) you get "Should not import the named export 'version' (imported as 'packageInfo')"

  3. Use the component constructor

    const zx = JSON.stringify(packageInfo);
    const zxj = JSON.parse(zx);
    console.log(zxj.version);
    
    this.version = zxj.version;
    
Tavares answered 19/3 at 1:4 Comment(0)
M
-2

I think you should only change the following import:

import { version } from '../../package.json';

with the following import:

import version from '../../package.json';
Mm answered 13/9, 2021 at 12:27 Comment(1)
Welcome to StackOverflow. What you are suggesting can be confusing because the imported object will contain the complete json object from the package.json file and not just the version. I think a better alternative would be: import packagejson from '../../package.json'; const {version} = packageJson;Bugbane

© 2022 - 2024 — McMap. All rights reserved.