網站搜尋

typescript - Webpack 4 構建會因 unsafe-eval 而破壞 CSP


當我嘗試執行我的 TypeScript + React Webpack 4 應用程式時,程式碼無法執行並出現錯誤:

未捕獲的 EvalError:拒絕將字串作為 JavaScript 進行評估,因為在以下內容安全策略指令中「unsafe-eval」不是允許的腳本來源:「script-src 'self'」

然而,在生成的套件中,我在第1行發現以下段落:

/* [...] */ get(e,t,n)}},_=Function("return this")(),C=new Map([[Map,T],[Set,T],[ /* [...] */ 

當然,這立即被執行,導致上述錯誤。

依我看,似乎有些東西需要參考全域物件(也就是 window),並試圖透過調用 Function("return this")() 來取得它。

的確,如果我更改生成的 app.<hash>.js 並將 ,_=Function("return this")() 替換為簡單的 ,_=window,一切都能正常運作,並且沒有任何 CSP 的抱怨。

package.json

{
  "name": "web",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --port 1234 --hot --inline --mode=development",
    "dev-twitch": "webpack-dev-server --port 1235 --hot --inline --mode=development",
    "build": "webpack -p",
    "build-dev": "webpack -d"
  },
  "author": "",
  "license": "UNLICENSED",
  "dependencies": {
    "@types/node": "^10.12.12",
    "@types/react": "^16.7.20",
    "@types/react-dom": "^16.0.11",
    "@types/react-transition-group": "^2.0.15",
    "autobind-decorator": "^2.3.1",
    "clean-webpack-plugin": "^1.0.1",
    "copy-webpack-plugin": "^4.6.0",
    "css-loader": "^1.0.1",
    "file-loader": "^2.0.0",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.5.0",
    "node-sass": "^4.11.0",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "react-easy-state": "^6.0.6",
    "react-transition-group": "^2.5.3",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "ts-loader": "^5.3.3",
    "typescript": "^3.3.1",
    "webpack": "^4.29.1",
    "webpack-cli": "^3.2.3",
    "webpack-dev-server": "^3.1.10",
    "zip-webpack-plugin": "^3.0.0"
  },
  "devDependencies": {}
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ZipPlugin = require('zip-webpack-plugin');

const htmlPlugins = [
  new HtmlWebpackPlugin({
    template: './src/index.html',
    inject: 'body',
    filename: 'index.html',
    chunks: ['app'],
  }),
];

let appIndex = './src/ts/_entry.tsx';
let outDir = 'dist';

module.exports = (env) => {
  const devMode = process.argv.find(v => v.includes('webpack-dev-server'));

  const styleLoader = devMode ? 'style-loader' : MiniCssExtractPlugin.loader;
  const cssPlugins = [];
  if (!devMode) {
    cssPlugins.push(
      new MiniCssExtractPlugin({
        filename: '[name].[hash].css',
        chunkFilename: '[id].[hash].css',
      })
    );
  }

  return ({
    entry: {
      app: appIndex,
    },
    output: {
      path: path.resolve(__dirname, outDir),
      filename:  '[name].[hash].js'
    }, resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: ['.ts', '.tsx', '.js'],
      alias: {
        src: path.resolve(__dirname, 'src/')
      }
    },
    devtool: 'hidden-source-map',
    node: {
      global: false,
    },
    plugins: [
      ...htmlPlugins,
      ...cssPlugins,
      new CleanWebpackPlugin('./' + outDir),
      new CopyWebpackPlugin([{
        from: './src/assets',
        to: './assets/'
      }]),
      new ZipPlugin({
        filename: 'dist-twitch.zip',
        path: __dirname,
      }),
    ],
    module: {
      rules: [
        { test: /\.tsx?$/, use: 'ts-loader' },
        { test: /\.(svg|woff|ttf|eot|woff2|otf)$/, use: 'file-loader' },
        { test: /\.(png|jpg|jpeg)$/, use: 'file-loader' },
        { test: /\.scss$/, use: [styleLoader, 'css-loader','sass-loader'] },
        { test: /\.css$/, use: [styleLoader, 'css-loader'] },
      ]
    },
    devServer: {
      clientLogLevel: 'error',
      overlay: true,
      proxy: {
        '/join': 'http://localhost',
      },
    }
  });
}

我該如何修改構建,才能不必手動處理結果?我如何才能最好地找出是哪個模組負責出錯的程式碼?

答案#1

我透過在我的設定中加入 'devtool: "source-map"' 來解決這個問題。請見下方。

const clientConfig = {
    mode: 'production',
    target: 'web',
    devtool: "source-map",
    entry: {
      ...
    },
    module: {
       rules: [
          ...
       ],
    },
    output: {
       ...
    },
    resolve: {
       ...
    } 
}

module.exports = [clientConfig]

我在這裡發現了這個解決方法。