【问题标题】:Webpack chunking. No content appearing - chunks not loadedWebpack 分块。没有内容出现 - 未加载块
【发布时间】:2018-06-25 03:27:28
【问题描述】:

我一直在努力解决这个烦人的问题,但我敢肯定,这是一个简单的问题。 我正在尝试将我的 bundle.js 分成块以优化网站加载时间。

这是我的 webpack.config 文件:

module.exports = {
devServer: {
historyApiFallback: true
},
entry: {
index: ["./src/index.js"],
vendor: [
  "react",
  "react-dom",
  "react-redux",
  "react-router",
  "react-router-dom",
  "redux"
]
},
output: {
path: __dirname + '/public/views',
filename: "[name].js",
publicPath: "/views/"
},
module: {
loaders: [
  {
    test: /\.js$/,
    loader: "babel-loader",
    exclude: [/node_modules/, /pdfmake.js$/]
  },
  {
    test: /\.json$/,
    loader: "json-loader"
  }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
  name: "vendor",
  filename: "vendor.js",
  minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
  name: "meta",
  chunks: ["vendor"],
  filename: "meta.js"
}),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
  title: "Deals",
  filename:  __dirname + "/views/index.ejs",
  template: __dirname + "/views/template.ejs",
  inject: false
}),
new PreloadWebpackPlugin({
  rel: "preload",
  as: "script",
  include: "all"
}),
new webpack.optimize.OccurrenceOrderPlugin(),
]
};

这是我简化的 index.ejs,通过运行 webpack 代码创建的文件,来自 template.ejs 的结果:

<!DOCTYPE html>
<html lang="en">

<head>

    <link href="/pace.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes">
    <meta charset="utf-8">
    <link rel="stylesheet" href="/style.css">
    <link rel="canonical" href="http://verygoodprof.fr/" />
    <link rel="preload" as="script" href="/views/index.js">
    <link rel="preload" as="script" href="/views/vendor.js">
    <link rel="preload" as="script" href="/views/meta.js">
</head>

<body>

    <noscript>
        <a href="http://enable-javascript.com/">Javascript must me enabled to use this site.</a>
    </noscript>

    <div class="text-center root" id="root">

    </div>

</body>

</html>

在这里,我看到我有我的预加载块,根据需要动态写入,并且这些块位于正确的文件夹中,是在运行 webpack 代码后创建的。

这是我的 index.js 文件(React),声明为 webpack.config 文件中的索引条目

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <AppInit>
      <BrowserRouter>
        <div style={{ height: "100%" }}>
          <ProfRegisteringModal />
          <Switch>
            {/* <Route path="/inscription/:user" component={Registering} />
            <Route path="/inscription" component={Registering} />
            <Route path="/connexion" component={SigningIn} />
            <Route path="/equipe" component={TeamPres} />
            <Route path="/" component={AppContainer} /> */}
            <Route
              path="/inscription/:user"
              getComponent={(location, callback) => {
                require.ensure(
                  [],
                  function(require) {
                    callback(
                      null,
                      require("./components/registering/registering_landing_page.js")
                    );
                  },
                  "registerChunk"
                );
              }}
            />
            <Route
              path="/inscription"
              getComponent={(location, callback) => {
                require.ensure(
                  [],
                  function(require) {
                    callback(
                      null,
                      require("./components/registering/registering_landing_page.js")
                    );
                  },
                  "registerChunk"
                );
              }}
            />
            <Route
              path="/connexion"
              getComponent={(location, callback) => {
                require.ensure(
                  [],
                  function(require) {
                    callback(
                      null,
                      require("./containers/registering/signing_in.js")
                    );
                  },
                  "signinChunk"
                );
              }}
            />
            <Route
              path="/equipe"
              getComponent={(location, callback) => {
                require.ensure(
                  [],
                  function(require) {
                    callback(null, require("./components/team_pres.js"));
                  },
                  "teampresChunk"
                );
              }}
            />
            <Route
              path="/"
              getComponent={(location, callback) => {
                require.ensure(
                  [],
                  function(require) {
                    callback(null, require("./containers/app_container.js"));
                  },
                  "appContainerChunk"
                );
              }}
            />
          </Switch>
        </div>
      </BrowserRouter>
    </AppInit>
  </Provider>,
  document.querySelector(".root")
);

我注意到的第一件事是应该为 vendormeta 而构建的块是正确构建的,但不是为我的内部反应组件构建的。但这不是主要问题,事实上,在本地运行服务器时,我根本看不到我的 react 应用。当我在控制台中签入时,index.ejs 文件已正确加载。

使用包含所有内容(无块)的简单 bundle.js 文件时,一切正常。使用 index.ejs 将其指向为

<script src="/views/bundle.js"></script>

非常感谢您的帮助!

编辑

这个 webpack.config 文件使它工作(感谢@margaretkru):

module.exports = {
  devServer: {
    historyApiFallback: true
  },
  entry: {
    app:"./src/index.js",
    vendor: [
      "axios",
      "jquery",
      "react",
      "react-dom",
      "react-redux",
      "react-router",
      "react-router-dom",
      "redux"
    ]
  },
  output: {
    path: __dirname + '/public/views',
    filename: "[name].js",
    publicPath: "/views/"
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: [/node_modules/, /pdfmake.js$/]
      },
      {
        test: /\.json$/,
        loader: "json-loader"
      }
    ]
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      filename:  __dirname + "/views/index.ejs",
      template: __dirname + "/views/template.ejs",
      inject: 'body',
      chunks: ['vendor', 'app'],
      chunksSortMode: 'manual'
    }),
    new PreloadWebpackPlugin({
      rel: "preload",
      include: ["vendor", "app"]
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
  ]
};new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      minChunks: Infinity
    }),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      filename:  __dirname + "/views/index.ejs",
      template: __dirname + "/views/template.ejs",
      inject: 'body',
      chunks: ['vendor', 'app'],
      chunksSortMode: 'manual'
    }),
    new PreloadWebpackPlugin({
      rel: "preload",
      include: ["vendor", "app"]
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
  ]
};

真正的问题不是加载脚本的顺序,而是我在“预加载”它们之后实际上并没有加载脚本:HTMLWebpackPlugin 的“inject”行提供了帮助,因为它注入了这两行:

<script src="/views/vendor.js"/> 
<script src="/views/app.js"/> 

在我的 index.ejs 正文中

【问题讨论】:

  • 所以我看到index.ejs 中加载的脚本顺序不正确,首先应该加载vendor.jsmeta.js,然后才加载index.js。但是我不明白为什么顺序是错误的。

标签: javascript reactjs webpack chunks chunking


【解决方案1】:

index.ejs 中加载的脚本顺序不正确。现在是:

<link rel="preload" as="script" href="/views/index.js">
<link rel="preload" as="script" href="/views/vendor.js">

这意味着您的index.js 将在vendor.js 之前加载,从而导致您的应用根本不会出现。首先应该加载应用程序的所有依赖项 (vendor.js),然后才加载 index.js,因为在执行自定义代码时需要存在依赖项。所以应该是:

<link rel="preload" as="script" href="/views/vendor.js">
<link rel="preload" as="script" href="/views/index.js">

编辑:

正如我们最终发现的那样,问题不在于脚本的顺序,而是由于脚本实际上并未加载到 html 中。为此,它们需要在HtmlWebpackPlugin 中作为块添加并注入index.html

 new HtmlWebpackPlugin({
      title: "Deals",
      filename:  __dirname + "/views/index.ejs",
      template: __dirname + "/views/template.ejs",
      inject: 'body',
      chunks: ['vendor', 'index']
    })

此外,块meta 的配置已被完全删除。其余所有配置(包括PreloadWebpackPlugin)都很好。

【讨论】:

  • 感谢您的回答。您提出的建议不起作用。顺序仍然不正确,即使我在 index.ejs 中手动更改顺序,网站也没有加载
  • 您在控制台中看到任何错误吗?如果你发了,你能把它们贴出来吗?
  • 你说得对,我可以删除它吗?我认为这是“捆绑”其他块的东西?
  • 我不确定你的意思:) 我会使用this 配置,最简单的配置,并测试它是否有效。如果它没有尝试完全删除PreloadWebpackPlugin,看看是否有变化。
  • 完美!我更新了答案,以便其他人遇到同样的问题时可以帮助他们:)
猜你喜欢
  • 1970-01-01
  • 2020-09-30
  • 2021-04-25
  • 2021-03-29
  • 2015-07-15
  • 2016-01-24
  • 2017-12-04
  • 2016-02-26
  • 1970-01-01
相关资源
最近更新 更多