如何移除Webpack构建中的eval与Function构造函数以规避CSP问题
Absolutely, there are straightforward fixes to eliminate eval and Function constructor usage from your Vue app built with Webpack—so it complies with browser extension CSP rules. Here's how to tackle each source of the problem:
1. Adjust Webpack's devtool Configuration
The most common culprit for eval in compiled code is Webpack's default devtool setting, which uses eval to wrap modules for faster development builds. To fix this:
- For production builds: Use a devtool that doesn't rely on
eval, likesource-mapornosources-source-map(the latter hides source code from end users, which is often preferred for extensions). - For development builds: Opt for
cheap-module-source-mapinstead of the defaulteval-cheap-module-source-mapto avoidevalwhile still keeping source maps for debugging.
Add this to your vue.config.js (or webpack.config.js if you're using raw Webpack):
module.exports = { devtool: process.env.NODE_ENV === 'production' ? 'source-map' : 'cheap-module-source-map' };
2. Disable Vue's Runtime Compiler
Vue's full build includes a runtime compiler that uses new Function() to compile templates on the fly. For extensions, you don't need this—all your templates should be pre-compiled via .vue files (handled by vue-loader).
To disable the runtime compiler:
- In
vue.config.js:module.exports = { runtimeCompiler: false }; - If you're configuring Webpack directly, set an alias to use Vue's runtime-only build:
resolve: { alias: { 'vue$': 'vue/dist/vue.runtime.esm.js' } }
This removes all Function constructor usage related to template compilation.
3. Audit Third-Party Dependencies
Sometimes, eval or Function can come from third-party libraries. Use the web-ext lint output to pinpoint which dependencies are causing violations. Then:
- Check if the library has a CSP-compliant version (many popular packages offer builds that avoid unsafe code).
- Replace the library with an alternative that doesn't use
eval/Functionif no compliant version exists.
4. Optimize Minification with Terser
Ensure your minifier (Terser, the default in Webpack 4+) is configured to strip any remaining unsafe code. Add this to your Webpack optimization settings:
const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimizer: [ new TerserPlugin({ terserOptions: { compress: { unsafe_eval: false, // Explicitly disable unsafe eval optimizations drop_console: true // Optional: Clean up console logs for production }, mangle: true, format: { comments: false } } }) ] } };
Verify the Fix
After making these changes:
- Rebuild your app with
npm run build(or your build command). - Search the compiled
build.jsfile for instances ofeval(ornew Function(to confirm they're gone. - Run
web-ext lintagain—your CSP violations should be resolved.
内容的提问来源于stack exchange,提问作者Akansh

