gpt4 book ai didi

javascript - 如何在preact中延迟加载组件?

转载 作者:行者123 更新时间:2023-12-01 00:02:03 25 4
gpt4 key购买 nike

我的目标是在构建时获得两个 bundle ,一个用于 index.tsx 文件,另一个用于 lazy.tsx 文件。我很确定我只是在某个地方缺少一两个选项。

GitHub MCVE - example project link

文件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;

Webpack 配置

{
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 代码分割的预期生成多个包。

编辑:这是 working example project 的链接

最佳答案

您的配置存在两个问题。

首先进行 TypeScript 配置:

{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"jsx": "react",
"jsxFactory": "h",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},

"include": [
"src/**/*.tsx"
]
}

要记住的两个重要属性是:

  1. 模块:'ESNext'
  2. moduleResolution:'节点'

一旦将 module 设置为 ESNext,您就无法在 TypeScript 中编写 Webpack 配置,因为它期望模块为 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;

这应该可以解决您的问题。

关于javascript - 如何在preact中延迟加载组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60656036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com