Import only webpack variable value

I am compiling code that requires a version value from package.json :

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

and when I look at the .js file that webpack displays, I see the whole package.json !

How can i avoid this?

My setup:

 plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.(js|css)$/, threshold: 10240, minRatio: 0.8 }), ] 

My version of the web package is 3.8.1

+5
source share
2 answers

I usually use DefinePlugin

 // webpack.config.js // getting the version const package = require("./package.json"); const version = package.version; plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': version, }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.(js|css)$/, threshold: 10240, minRatio: 0.8 }), ] 

Now in your code all you have to do is use process.env.VERSION and you will get the version of your packages.

Hope this helps

+7
source

Modern versions of webpack support Tree shaking ( https://webpack.js.org/guides/tree-shaking/ ), but it only works if export directives are configured according to a special scheme, it includes independent import of names for each object. In this case, webpack can run an analysis dependency graph and include only the required objects. In addition, the import directive does not support destruction - this is only the syntax for named imports, so a large JS object will always be imported in a monolithic style.

Import by value is not available by definition, because webpack only performs a bundle for a set of files with source code and, possibly, dependencies of custom resources. Real imports into ES6 modules, which are already supported on most platforms today, also do not import values ​​- instead, they are required. https://ponyfoo.com/articles/es6-modules-in-depth#bindings-not-values .

Of course, the original problem can be solved using the webpack replace or alias plugins. Just save version in some independent file or string constant and replace it with linking. The simplest solution is

 import version from 'PACKAGE_VERSION' 

and then configure external with a callback https://webpack.js.org/configuration/externals/ like this

 externals: [ function(context, request, callback) { if (request === 'PACKAGE_VERSION'){ return callback(null, 'exports.default = ' + JSON.stringify(JSON.parse(fs.readFileSync('package.json')).version)); } callback(); } ], 
+2
source

Source: https://habr.com/ru/post/1273185/


All Articles