Type Script+React+webpackシンプルフレームワーク
7200 ワード
プロジェクトディレクトリの作成
TypeScriptファイルはsrcフォルダに格納、TypeScriptコンパイラでコンパイルし、webpack処理してbundleを生成します.jsファイルは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
Type Scriptプロファイルの追加
プロジェクトルートの下にtsconfigを追加する.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
Demoコード作成
import * as React from 'react';
export interface HelloProps {
compiler: string;
framework: string;
}
export class Hello extends React.Component {
render() {
return Hello from { this.props.compiler } and { this.props.framework } !;
}
}
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Hello } from './components/greeter';
ReactDom.render(
"typescript" framework="react" />,
document.getElementById('demo')
)
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!title>
head>
<body>
<div id="demo">div>
<script src="./node_modules/react/umd/react.development.js">script>
<script src="./node_modules/react-dom/umd/react-dom.development.js">script>
<script src="./dist/bundle.js">script>
body>
html>
Webpack構成
プロジェクトルートディレクトリの下にwebpackを作成します.config.js
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
// Enable sourcemaps for debugging webpack's output.
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.
externals: {
"react": "React",
"react-dom": "ReactDOM"
},
};
ビルドコマンドの追加
...
"scripts": {
"build": "webpack"
},
...
npm run build
転載先:https://juejin.im/post/5c6630c86fb9a049c232f3aa