Using a Module Bundler
If you're utilizing a module bundler like webpack or rollup (which is recommended for npm packages), you can easily achieve this by...
commonjs
window.package = require('./package.json');
esm
import pkg from './package.json' assert {type: 'json'};
window.package = pkg;
The bundler will handle the import and bundle the json data into your output script, making it accessible in a browser via window.package.version
.
If you are using Vite or rollup as your module bundler, to enable import assertions, make use of the
@babel/plugin-syntax-import-assertions
plugin. Here is an example with React:
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [
react({
babel: {
plugins: ["@babel/plugin-syntax-import-assertions"],
},
}),
],
});
Without a Module Bundler
If you do not have a module bundler configured, you can still achieve this functionality by leveraging modules
index.html
<html>
<head>
<title>Import package.json</title>
</head>
<body>
<script type="module">
import pkg from "./package.json" assert { type: "json" };
alert(pkg.version);
</script>
</body>
</html>
package.json
{
"name": "js",
"version": "0.0.0",
"private": true,
"dependencies": {}
}
Note: Trying to open index.html
locally may result in a CORS error. It is necessary to serve the file. An easy way to serve this website on macOS is by using python..
python3 -m http.server 9000
Afterwards, access localhost:9000
in your browser to view your package version
https://i.sstatic.net/OhK3Q.png