gpt4 book ai didi

javascript - 我不知道如何在 svelte.js 中使用生命周期

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:30 26 4
gpt4 key购买 nike

假设

我对前端了解不多。

想做

我想将生命周期与 sveltejs 一起使用。

发生错误

出现以下错误,生命周期方法不可用:

ERROR in ./node_modules/svelte/index.mjs
Module not found: Error: Can't resolve './internal' in 'C:\project\test_svelte_lifecycle\node_modules\svelte'
@ ./node_modules/svelte/index.mjs 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167 1:0-167
@ ./test-component.svelte
@ ./app.js
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

这是什么原因造成的?

我从公式中得到了这个代码。然而,出现了错误,并没有起作用。我不知道为什么。

有同样错误的人做了一个github问题。

https://github.com/sveltejs/svelte/issues/2937

我相应地修改了我的代码,但它不起作用。

代码

package.json

{
"dependencies": {
"svelte": "^3.17.2",
"svelte-loader": "^2.13.6",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"peerDependencies": {
"svelte": "^3.17.2"
}
}
<小时/>

webpack.config.js

const path = require('path');

module.exports = {
entry: path.resolve(__dirname, 'app.js'),

output: {
path: path.resolve(__dirname, './dist/'),
filename: 'bundle.js'
},

resolve: {
alias: {
svelte: path.resolve('node_modules', 'svelte')
},
extensions: ['.svelte'],
mainFields: ['svelte', 'browser', 'module', 'main']
},

module: {
rules: [
{
test: /\.(html|svelte)$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
customElement: true
}
}
}
]
}
};
<小时/>

测试组件.svelte

<script>
import { onMount } from "svelte";

let hello = "hello";
let world = "world";

onMount(async () => {
hello = "hello hello";
});
</script>

<svelte:options tag="test-component" />

<div>{hello} and {world}</div>
<小时/>

app.js

import TestComponent from './test-component.svelte';
<小时/>

index.html

<html>

<head>
<meta charset="utf8">
<script src="./dist/bundle.js"></script>
</head>

<body>
<test-component></test-component>
</body>

</html>

最佳答案

我认为您的错误是因为您的 webpack 的 resolve.extensions 中没有 .mjs 。错误消息 ./internal 指出的文件实际上是一个 .mjs 文件,但您只有 .svelte 扩展名...

应该是这样的:

  resolve: {
alias: {
svelte: path.resolve('node_modules', 'svelte'),
},
extensions: ['.mjs', '.js', '.svelte'],
mainFields: ['svelte', 'browser', 'module', 'main'],
},

关于javascript - 我不知道如何在 svelte.js 中使用生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59856447/

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