我正在尝试使用可重用的JS从服务器加载某些文件,但是如果我将代码放在一起,或者将文件放在单独的文件中,但我不明白为什么,这会以不同的方式工作
一起:
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');
});
但是如果我像这样拆分代码是行不通的: 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
import addAssetsFromManifest from './addAssetsFromManifest';
document.addEventListener('DOMContentLoaded', () => {
addAssetsFromManifest('path/js/file.js');
});
根本不起作用。我不确定这是否值得与webpack相关,如果可以,我将共享package.json
和webpack.config.js
任何想法
答案 0 :(得分:1)
尝试使用require和modules.export
module.export = function addAssetsFromManifest(file){......}
和
const addAssetsFromManifest = require("./addAssetsFromManifest")