[英]Creating a reusable JS file - Import - export not working
I am trying to have a reusable JS to load some files form the server, but this is working differently if I have the code together or if I have on separate files and I dont understand why 我正在尝试使用可重用的JS从服务器加载某些文件,但是如果我将代码放在一起或将文件放在单独的文件中并且我不明白为什么会这样做,则工作方式会有所不同
All together: 全部一起:
require('isomorphic-fetch');
function addAssetsFromManifest(file) {
const loadManifest = fetch('/path/manifest.json');
loadManifest.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
const loadJson = resp.json();
loadJson.then((json) => {
const scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = `/${json[file]}`;
const { body } = document;
body.appendChild(scriptTag);
return json;
});
return loadJson.then(Promise.reject.bind(Promise));
}
return loadManifest.then(Promise.reject.bind(Promise));
});
}
document.addEventListener('DOMContentLoaded', () => {
addAssetsFromManifest('path/js/file.js');
});
but if I split the code like this is not working: addAssetsFromManifest.js: 但是,如果我像这样拆分代码不起作用:addAssetsFromManifest.js:
require('isomorphic-fetch');
export default function addAssetsFromManifest(file) {
const loadManifest = fetch('/path/manifest.json');
loadManifest.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
const loadJson = resp.json();
loadJson.then((json) => {
const scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = `/${json[file]}`;
const { body } = document;
body.appendChild(scriptTag);
return json;
});
return loadJson.then(Promise.reject.bind(Promise));
}
return loadManifest.then(Promise.reject.bind(Promise));
});
}
loader.js loader.js
import addAssetsFromManifest from './addAssetsFromManifest';
document.addEventListener('DOMContentLoaded', () => {
addAssetsFromManifest('path/js/file.js');
});
is not working at all. 根本不工作。 I am not sure if this is related worth webpack or not, if yes I will share
package.json
and webpack.config.js
我不确定这是否值得webpack相关,如果是,我将共享
package.json
和webpack.config.js
Any ideas 有任何想法吗
Try using require and modules.export 尝试使用require和modules.export
module.export = function addAssetsFromManifest(file){......}
and 和
const addAssetsFromManifest = require("./addAssetsFromManifest")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.