小技巧:如何判断当前的代码被混淆了?
2016-12-24 · 291 chars · 2 min read
不知道你有没有思考过一个问题,当前的很多框架&库,都在开发环境和生产环境下有不同的表现。例如 react,vue 等,可以判断props 的类型,并且在开发环境下打印警告信息,而生产环境则不会。这是如何做到的呢?
Redux 提供了一种很妙的方案:
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (
process.env.NODE_ENV !== 'production' &&
typeof isCrushed.name === 'string' &&
isCrushed.name !== 'isCrushed'
) {
warning(
"You are currently using minified code outside of NODE_ENV === 'production'. " +
'This means that you are running a slower development build of Redux. ' +
'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' +
'to ensure you have the correct code for your production build.',
)
}
我们知道,目前 uglifyjs 会在混淆代码的同时,更改一些变量、函数名,以减小 js 文件的体积。而 redux 就巧妙的利用了这点,判断出了当前代码的环境。


