【发布时间】:2017-04-26 23:07:36
【问题描述】:
我的意图是有这样的目录结构:
- /my-project/
-- /src/ (here are all .tsx files located)
-- /dist/
- index.html
- /build/
-bundle.js
-- /node_modules/
-- package.json
-- tsconfig.json
-- webpack.config.js
所以,我想要在 /dist 子目录中手动创建我的 index.html,并在其中包含 /build 子目录,其中 webpack 制作的 app.js 所在的位置。
当我保存一些位于我的 /src 目录中的 .tsx 文件时,我希望 webpack 自动重建 app.js 和 webpack-dev-server 自动反映更改。
我的package.json 看起来像这样:
{
"name": "my-project",
"version": "1.0.0",
"description": "My first React App",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --content-base ./dist --hot --inline --colors --port 3000 --open",
"build": "webpack --config webpack.config.js --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "AndreyKo",
"license": "ISC",
"devDependencies": {
"@types/react": "^0.14.54",
"@types/react-dom": "^0.14.19",
"jquery": "^3.1.1",
"source-map-loader": "^0.1.5",
"ts-loader": "^1.3.0",
"typescript": "^2.1.4",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1"
}
}
我的webpack.config.js:
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "app.js",
publicPath: "/dist/",
path: "./dist/build/"
},
dev_tool: "source-map",
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader'}
],
preloaders: [
{test: /\.js$/, loader: 'source-map-loader'}
]
}
}
我的index.html:
<!DOCTYPE html>
<html>
<body>
<div id="app-container"></div>
</body>
<script src="./build/app.js"></script>
</html>
我的index.tsx 文件如下所示:
import * as jQuery from 'jquery';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
function appOutput() {
ReactDOM.render(<div>Hello, we are talking from React!</div>, document.getElementById("app-container"));
}
appOutput();
我已经对终端执行了命令:
npm run build
npm run start
所以 app.js 被创建并且 webpack-dev-server 开始工作并在浏览器中打开页面。到目前为止一切都很好。但是,当我更改 index.tsx 中的文本并保存此文件时,没有任何更改,我尝试刷新浏览器页面,文本保持不变并且 app.js 没有重新构建。 要进行文本更改,我必须通过发出“npm run build”再次从终端手动重建 app.js 和 webpack。
如何改进我的工作流程以使 /src 文件夹中的更改自动反映在我的 dist/build/app.js 文件中,而无需手动重建它?
【问题讨论】:
-
您正在寻找的是(可能)热重载。 Dan Abramov 有一个react/hot reloading boilerplate repo,应该会有所帮助。我没有找到任何使用 Typescript 的好例子,但是 I have a project that is doing it that might help if you need direction.
标签: javascript reactjs typescript webpack webpack-dev-server