[英]How to lazy load components in preact?
我的目標是在構建時獲得兩個包,一個用於index.tsx
文件,另一個用於lazy.tsx
文件。 我很確定我只是在某處缺少一兩個選項。
GitHub MCVE -示例項目鏈接
src/index.tsx
import { render, h } from 'preact';
let a: any = null;
let b = 0;
const App = () => (
<div>
<button
onClick={() => {
import('./lazy').then(M => {
console.log('LOADED COMPONENT');
a = <M.default />;
b++;
render(<App></App>, document.body);
});
}}
>
test
</button>
{a} {b}
</div>
);
render(<App></App>, document.body);
src/lazy.tsx
import { h, FunctionComponent } from 'preact';
console.log('LAZY');
interface LazyProps {}
const Lazy: FunctionComponent<LazyProps> = props => {
const {} = props;
return <div>LAZY LOADED COMPONENT</div>;
};
export default Lazy;
{
entry: {
index: `${__dirname}/src/index.tsx`
},
output: {
path: resolve(__dirname, 'dist'),
chunkFilename: '[name].[id].js',
filename: '[name].bundle.js'
},
plugins: [new HtmlWebpackPlugin()],
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: [/node_modules/]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
optimization: {
minimize: false
}
}
上面的代碼運行良好,沒有任何錯誤,但它沒有像預期的那樣使用 Webpack 代碼拆分生成多個包。
編輯:這是工作示例項目的鏈接
您的配置有兩個問題。
首先是您的 TypeScript 配置:
{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"jsx": "react",
"jsxFactory": "h",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*.tsx"
]
}
要記住的兩個重要的屬性是:
module
:'ESNext'moduleResolution
:'節點' 一旦你將module
設置為ESNext
,你就不能在 TypeScript 中編寫你的 Webpack 配置,因為它期望 module 是commonjs
。 因此將其更改為 CommonJS 格式的普通 JS:
const Configuration = require('webpack').Configuration;
const Dev = require('webpack-dev-server').Configuration;
const resolve = require('path').resolve;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const config = {
entry: {
index: `${__dirname}/src/index.tsx`
},
output: {
path: resolve(__dirname, 'dist'),
chunkFilename: '[name].[id].js',
filename: '[name].bundle.js'
},
plugins: [new HtmlWebpackPlugin()],
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: [/node_modules/]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
optimization: {
minimize: false
}
};
module.exports = config;
這應該可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.