本文演示如何在ts项目中添加antd,并支持按需加载
webpack从0开始搭建react的ts开发环境(7)
demo https://github.com/757566833/webpack-guide
1.加入antd的库
yarn add antd --dev
2.修改src/app.tsx
import {Button} from "antd";
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
public render() {
return (
<div>
<Button >hello antd</Button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
3.npm run webpack
4.打开dist/index.html
5.发现样式丢了,选取ts-import-plugin方案
yarn add ts-import-plugin --dev
6.webpack.config.js修改
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const tsImportPluginFactory = require("ts-import-plugin");
module.exports = {
entry: './src/app.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
// 引入了组件 规模变大,现在设置为开发模式
mode: 'development',
module: {
rules: [{
test: /\.tsx?$/,
loader: "ts-loader",
// 这里面新加
options: {
transpileOnly: true,
getCustomTransformers: () => ({
before: [tsImportPluginFactory({
libraryName: "antd",
libraryDirectory: "lib",
style: true,
})],
}),
compilerOptions: {
module: "es2015",
},
},
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
},
{
loader: "css-loader",
},
],
exclude: /node_modules/,
},
{
test: /\.less$/,
use: [{
loader: MiniCssExtractPlugin.loader,
},
{
loader: "css-loader",
},
{
loader: "less-loader",
},
],
},
{
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: 'css-loader',
}, {
loader: 'sass-loader'
}],
exclude: /node_modules/
},
]
},
plugins: [
new HtmlWebpackPlugin({
title: "test",
template: path.resolve(__dirname, "template.html"),
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: "app.css",
// chunkFilename: "[id].[hash].css",
// ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
]
};
网友评论