How to remove eval and Function constructor from webpack build to avoid CSP issues

Do you want to request a feature or report a bug?
BUG : Stackoverflow Link

What is the current behavior?
It gives both eval and Function contructor which is not required

try {
    // This works if eval is allowed (see CSP)
    g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
    // This works if the window reference is available
    if(typeof window === "object")
        g = window;
}

// Another method of build 
function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }

If the current behavior is a bug, please provide the steps to reproduce.

$ npm install -g vue-cli
$ vue init webpack-simple my-project
$ cd my-project
$ npm install
$ npm run prod

You can see in `build.js` having eval 

What is the expected behavior?
I expect that webpack should provide provision to build according to CSP policy as I am using runtime vue which does not even require compiler.

Please mention other relevant information such as the browser version, Node.js version, webpack version and Operating System.

Node.js : 9.5.0

Tried it with latest config too.
Package.json

{
  "webpack": "^3.10.0",
  "babel-core": "^6.18.2",
  "babel-loader": "^7.1.2",
  "babel-preset-es2015": "^6.18.0",
  "babel-preset-stage-2": "^6.24.1",
  "file-loader": "^0.9.0",
  "style-loader": "^0.18.2",
  "vue-loader": "^10.0.2"
}

Author: Fantashit

3 thoughts on “How to remove eval and Function constructor from webpack build to avoid CSP issues

  1. I was able to fix the first eval issue by setting node.global to false. This will avoid including this shim which includes an eval in a try/catch. Not sure if this will be confusing or clarifying but I only observed this CSP warning in Firefox and not Chrome.

  2. Disabling node or node.global might break your isomorphic/universal modules.

    Responsible for that eval call is the following code: https://github.com/webpack/webpack/blob/master/buildin/global.js#L8-L11

    If you remove it by setting node.global to false, will result in global being undefined in your code.

    How I solved the issue:

    1. Create a global.js file somewhere in your project:

      global.js

      module.exports = window
    2. Disable node.global in your webpack.config.js by setting it to false.

    3. Add the global.js by using webpacks provide plugin:

      webpack.config.js

      {
        ...
        node: {
          global: false
        },
        plugins: [
          ...
          new webpack.ProvidePlugin({
            global: require.resolve('./global.js')
          })
          ...
        ],
        ...
      }

    Please note, that you should only use this configuration, if the webpack.target is web.

Comments are closed.