2017-09-19 102 views
0

我正在使用HtmlWebpackPlugin的webpack。使用Flask服務器提供生成的index.html。 index.html在Flask服務器中調用的很好。但是,我認爲在我的webpack配置中有一個錯誤,導致app.bundle.js變壞。Webpack HtmlWebpackPlugin - 捆綁文件提供HTML?

在瀏覽器的開發人員工具,我可以看到錯誤是

Uncaught SyntaxError: Unexpected token <

當瀏覽器加載app.bundle.js,它似乎認爲它是index.html的副本。但是在我的本地計算機上,我可以看到app.bundle.js是webpack的Javascript包。

的WebPack配置文件

const path = require("path"); 
const HtmlWebpackPlugin = require('html-webpack-plugin'); 

module.exports = { 
    entry: './index.js', 
    output: { 
    path: path.resolve(__dirname, "static/dist"), 
    filename: '[name].bundle.[hash].js' 
    }, 
    plugins: [ 
    new HtmlWebpackPlugin({ 
     template: path.resolve(__dirname, 'index.template.ejs'), 
     showErrors: true, 
     hash: true, 
    }) 
    ], 
    module: { 
    rules: [ 
     { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, 
     { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }, 
     { 
     test: /\.css$/, 
     use: [ 
      "style-loader", 
      { 
      loader: "css-loader", 
      options: { importLoaders: 1, modules: true }, 
      }, 
      "sass-loader" 
     ], 
     }, 
     { 
     test: /\.(png|jpg|gif)$/, 
     use: [ 
      { 
      loader: 'file-loader', 
      options: {} 
      } 
     ] 
     }, 
     { 
     test: /\.svg$/, 
     loader: 'svg-inline-loader' 
     } 
    ], 

    }, 
    resolve: { 
    alias:{ 
     components: path.resolve(__dirname, './components'), 
     containers: path.resolve(__dirname, './containers'), 
     channels: path.resolve(__dirname, './channels'), 
     models: path.resolve(__dirname, './models'), 
     stores: path.resolve(__dirname, './stores'), 
     lib: path.resolve(__dirname, './lib') 
    }, 
    modules: ['components', "node_modules"], 
    extensions: ['.js', '.jsx'] 
    } 
}; 

HTML in bundled Javascript Source

回答

0

這個問題通過在JS源不能正常加載造成的。它低於實際的main.bundle。[hash] .js源代碼的兩個級別。

<script type="text/javascript" src="main.bundle.[hash].js"></script> 

本來應該

<script type="text/javascript" src="static/dist/main.bundle.[hash].js"></script> 

然而真正的問題是瀏覽器的回退。它無法正確找到源代碼,並挖出了需要失敗的腳本包含的HTMl文件。當它拉起HTML時,它最終讀取了一個JS文件。

我通過向我的webpack配置添加一個publicPath來解決這個問題。

module.exports = { 
... 
    output: { 
     ... 
     publicPath: 'static/dist' 
     ... 
    } 
... 
}