reactjs - React、Typescript 和 Webpack 将 bundle.js 添加到页面的问题
问题描述
当我构建我的项目时,它构建得很好,并创建了 bundle.js 文件,但是当导航到http://localhost:8080/的页面时,我在控制台中看到了警告:
Loading failed for the <script> with source “http://localhost:8080/dist/bundle.js”.
我对此感到非常困惑,因为似乎一切都在正确构建和启动。
我浏览了这些页面中的每一页:1 2 3 4并尝试了它们在那里显示的内容,但没有任何变化。
我的 webpack.config.js 文件:
"use strict"
const path = require('path');
module.exports = {
entry: './App.tsx',
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'dist')
},
devServer: {
publicPath: "/",
contentBase: "./public",
hot: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: "inline-source-map",
module: {
rules: [{
test: /\.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}]
}
};
tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowJs": true
},
"include": [
"App.tsx"
]
}
包.json
{
"name": "project",
"version": "1.0.0",
"private": true,
"main": "App.tsx",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.3.1",
"@babel/preset-react": "^7.0.0",
"@types/react": "^16.8.1",
"@types/react-dom": "^16.0.11",
"babel": "^6.23.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.0",
"react-hot-loader": "^4.6.5",
"source-map-loader": "^0.2.4",
"style-loader": "^0.23.1",
"ts-loader": "^5.3.3",
"tslint": "^5.12.1",
"tslint-react": "^3.6.0",
"typescript": "^3.3.1",
"webpack": "^4.29.1",
"webpack-cli": "^3.2.2",
"webpack-dev-server": "^3.1.14"
},
"dependencies": {
"awesome-typescript-loader": "^5.2.1",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-scripts": "2.1.3"
},
"scripts": {
"start": "webpack-dev-server --hot --inline",
"build": "webpack"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
App.tsx 就是这么简单,直到我可以让它与这个测试一起工作:
import * as React from "react";
import * as ReactDOM from "react-dom";
import "./App.css";
export interface Props {}
export interface State {}
class App extends React.Component<Props, State> {
public render(): JSX.Element {
return (
<div className="test">
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
作为参考,以防我遗漏了一些非常简单的东西,我的文件结构如下所示:
project
|- package.json
|- package-lock.json
|- tsconfig.json
|- tslint.json
|- webpack.config.js
|- App.tsx
|- App.css
|- /dist
|- bundle.js
|- /public
|- index.html
|- /node_modules
在将其切换到带有 React 的 Typescript 之前(我只使用带有 webpack 的 React,然后决定使用 typescript、react 和 webpack),它正在将 div 添加到根 div 没有问题,我希望能做到同样的事情,但是现在它只加载index.html
只有<div id="root"></div>
and的页面<script src="../dist/bundle.js"></script>
解决方案
好吧,原来这只是一个简单的问题。我猜 index.html 需要与 bundle.js 位于同一目录中。一旦我将 index.html 移动到 dist 中,它就可以正常工作。