我正在尝试从API动态导入react组件库。 js文件已成功获取。通天塔的移植也成功发生了。如果我像import Dummy from './components/js/Dummy.js'
这样从本地动态导入Dummy.js文件,它将起作用。但是,API导入失败,并出现以下错误。懒惰的反应也会发生相同的错误。我基本上想动态加载lib并将事件发布到它。我是新手,可以响应并进行前端开发。如果这太傻,请原谅!。
Error resolving module specifier: react
我的App.js
import React, { lazy, Suspense } from 'react';
import './App.css';
import ErrorBoundary from './ErrorBoundary';
class App extends React.Component {
render(){
const loader = () => import( /*webpackIgnore: true*/ `https://example.com/Dummy.js`);
const Dummy = ReactDynamicImport({ loader });
const LoadingMessage = () => (
"I'm loading..."
)
return (
<div className="App">
<h1>Simplewidget</h1>
<div id="simplewidget">
<ErrorBoundary>
<Suspense fallback={LoadingMessage}>
<Dummy />
</Suspense>
</ErrorBoundary>
</div>
</div>
);
}
}
export default App;
rollup.config.js,经过多次尝试,我到达了以下配置https://github.com/jaebradley/example-rollup-react-component-npm-package/blob/master/rollup.config.js
// node-resolve will resolve all the node dependencies
import resolve from '@rollup/plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import filesize from 'rollup-plugin-filesize';
import localResolve from 'rollup-plugin-local-resolve';
export default {
input: 'src/components/js/Dummy.js',
output: {
file: 'dist/Dummy.js',
format: 'es',
globals: {
react: 'React',
'react-dom': 'ReactDOM'
}
},
// All the used libs needs to be here
external: [
'react',
'react-dom'
],
plugins: [
babel({
exclude: 'node_modules/**',
}),
localResolve(),
resolve({
browser: true,
}),
commonjs(),
filesize()
]
}
Dummy.js。我在dist / dummy.js中验证了babel移植正确发生。我将转译的版本上传到我的静态托管站点。
import React from "react";
import ReactDOM from "react-dom";
class Dummy extends React.Component {
render() {
return (
<h1>Hello</h1>
);
}
}
export default Dummy;
在同一应用中,我有不同的目标来构建,启动服务器,创建汇总包等。因此,我非常有信心自己的汇总不会干扰应用程序的运行。
答案 0 :(得分:1)
汇总捆绑配置不正确。我实际上想用esm模块来尝试用commonjs插件创建es输出。 “ react”上的错误是因为未解决。必须使其使用window.Rerolling捆绑时反应。另外,应将App.js汇总为esm软件包,以使其动态导入Dummy.js。在包含app.js包的HTML中,我必须包含react和react js umd脚本。
export default {
input: "./src/components/js/Dummy.js",
output: {
file: './dist/Dummy.js',
format: 'esm'
},
plugins: [
babel({
exclude: "node_modules/**"
}),
resolve(),
externalGlobals({
"react": "window.React",
"react-dom": "window.ReactDOM",
})
]
};