【问题标题】:Webpack successfully compiled but does not show output in browserWebpack 编译成功但在浏览器中不显示输出
【发布时间】:2017-11-14 20:58:41
【问题描述】:

我项目中的 webpack 运行成功,但是当我到达所需的端口时,它会显示目录文件。您可以查看相同的图像。

我的 webpack.config.js

const path = require('path');

module.exports = {
  entry: './app/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    port: 8100
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
}

package.json

{
  "name": "react_router",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server"
  },
  "author": "vinay",
  "license": "ISC",
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router": "^2.0.1"
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  }
}

main.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'
ReactDOM.render(<App />, document.getElementById('root'));

app.js

import React, {Component} from 'react';
import {Router, Route, Link, IndexRoute, hashHistory, browserHistory} from 'react-router';

const App = () => <h1>Hello World</h1>

export default App

输出==>

任何帮助将不胜感激。

【问题讨论】:

  • 你没有 index.html 文件供 webpack-dev-server 显示。添加一个 index.html 文件,其中包含指向您的捆绑包的链接。
  • 我在 App 目录中有 index.html 文件。但是如何将它添加到捆绑包中?
  • 你需要在index.html中提供bundle脚本url
  • 阅读docs,它非常简单。

标签: reactjs webpack webpack-dev-server jsx


【解决方案1】:

编辑的答案: 我能够让它工作:

1) 在根文件夹下创建实际的 dist 目录 2) 使 webpack.config.js 中的输出如下所示:

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: 'bundle.js',
  publicPath: '/dist/'
},

它会告诉 webpack 从哪里为你的应用程序提供服务。

3) 将以下脚本添加到您的 package.json 中

    "build": "webpack -p"

它将构建 bundle.js 文件

另外,您的 dist 目录中需要一个 index.html 文件,如下所示:

<!DOCTYPE html>
  <html lang="en">
    <head>
     <meta charset="UTF-8">  
     <title>Application<title>
   </head>
   <body>
     <div id="app"></div>
     <script src="bundle.js"></script>
   </body>
</html>

然后,你运行你的构建脚本,然后你可以运行 webpack 服务器,它应该可以工作了

【讨论】:

  • 你真的有 dist 目录吗?您也可以发布构建输出吗?
  • 不,它也没有创建 dist 文件夹,但它说 webpack 编译成功。
  • 这是我设置输出目录的方式: const buildDirectory = './public/js/'; webpackConfig = { ... 输出:{ 路径:path.resolve(buildDirectory),文件名:'app.js' } ... }
  • 你能解释一下你为什么这样做 const buildDirectory = './public/js/';
  • 它只是为了让我可以直接在配置文件的顶部更改我的构建目录并在实际的配置目录中使用它。不管你是按照我的方式还是按照你的方式去做都没有关系。
猜你喜欢
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多