搗騰一周倦踢,一步一步造輪子??
嘗鮮
??引入 TypeScript 編寫更加安全的代碼,不再為類型煩惱
??使用 Webpack 3 打包
該文檔使用的是TypeScript
環(huán)境設(shè)置
下載和安裝 Node.js
下載和安裝依賴管理工具 Yarn
也可以使用npm 去安裝 yarn
npm install -g yarn
初始化項(xiàng)目
mkdir project
cd project
yarn init
安裝相關(guān)依賴
yarn add react react-dom
yarn add @types/node @types/react @types/react-dom @types/webpack webpack typescript awesome-typescript-loader source-map-loader -D
添加 TypeScript 配置文件
tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"strict": true,
"experimentalDecorators": true,
"sourceMap": true,
"noImplicitAny": true,
"module": "esnext",
"moduleResolution": "node",
"target": "es5",
"jsx": "react",
"lib": [
"esnext",
"dom"
]
}
}
創(chuàng)建 Webpack 配置文件
webpack.config.js
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
{test: /\.(ts|tsx)$/, use: [{loader: 'awesome-typescript-loader'}] },
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
}
};
編寫入口
src/index.tsx
import * as React from 'react'
import * as ReactDOM from 'react-dom'
export class Hello extends React.Component<{}, {}> {
render() {
return <h1>Hello Tyscript</h1>
}
}
ReactDOM.render(
<Hello/>,
document.getElementById('app')
)
執(zhí)行 webpack 打包即可
Webpack 扯淡篇
代碼分割
yarn add react-loadable
yarn add @types/react-loadable -D
Example
import Loadable from 'react-loadable'
import * as React from 'react'
const Main = Loadable({
loader: () => import('../components/Main'),
loading: (() => null),
})
export default class App extends React.Component {
render() {
return <Main/>;
}
}
Webpack也需要做相應(yīng)的配置
webpack.config.js
output: {
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js'
}
css抽取
yarn add extract-text-webpack-plugin -D
webpack.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
}]
})
},
]
},
plugins: [
new ExtractTextPlugin({
filename:
'static/css/[name].[contenthash:8].css',
allChunks: true
}),
]
js壓縮
yarn add uglifyjs-webpack-plugin -D
webpack.config.js
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
plugins: [
new UglifyJSPlugin({
sourceMap: true,
compress: {
warnings: false
},
comments: false,
})
]
提取公用模塊
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: (module) => module.context && module.context.indexOf('node_modules') !== -1,
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
]