标签:webp 初始 awesome ever win 根目录 安装 als 并且
官方文档:https://www.tslang.cn/docs/handbook/react-&-webpack.html
项目结构
demo/
├─ dist/
└─ src/
└─ components/
初始化
npm init
安装依赖
npm install -g webpack
npm install --save react react-dom @types/react @types/react-dom
npm install --save-dev typescript awesome-typescript-loader source-map-loader
demo根目录下创建tsconfig.json
,点击这里了解更多配置。
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
src/components目录下创建一个名为Hello.tsx:
import * as React from "react";
export interface HelloProps { compiler: string; framework: string; }
// ‘HelloProps‘ describes the shape of props.
// State is never set so we use the ‘{}‘ type.
export class Hello extends React.Component<HelloProps, {}> {
render() {
return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
}
}
src下创建index.tsx
:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Hello } from "./components/Hello";
ReactDOM.render(
<Hello compiler="TypeScript" framework="React" />,
document.getElementById("root")
);
demo根目录下创建index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
</head>
<body>
<div id="root"></div>
<!-- Dependencies -->
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
<!-- Main -->
<script src="./dist/bundle.js"></script>
</body>
</html>
demo根目录下创建webpack.config.js
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
mode:"development",
devtool: "source-map",
resolve: {
// Add ‘.ts‘ and ‘.tsx‘ as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a ‘.ts‘ or ‘.tsx‘ extension will be handled by ‘awesome-typescript-loader‘.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output ‘.js‘ files will have any sourcemaps re-processed by ‘source-map-loader‘.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
//避免把所有的React都放到一个文件里,因为会增加编译时间并且浏览器还能够缓存没有发生改变的库文件
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};
执行命令
webpack
在浏览器打开index.html
标签:webp 初始 awesome ever win 根目录 安装 als 并且
原文地址:https://www.cnblogs.com/sanhuamao/p/14404268.html