Blu*_*r86 6 rollupjs es6-modules
从 ES6 模块内的 URL 导入是完全有效的,因此我一直在使用这种技术在位于不同主机/端口的微服务之间重用模块:
import { authInstance } from "http://auth-microservice/js/authInstance.js"
Run Code Online (Sandbox Code Playgroud)
我正在接近一个发布周期,并开始沿着我通常的方式使用 rollup 捆绑到 IIFE。Rollup 似乎不支持从 URL 导入 es6 模块,我认为它应该支持,因为规范中允许这样做:(
module-name 要导入的模块。这通常是包含该模块的 .js 文件的相对或绝对路径名。某些捆绑商可能允许或要求使用扩展;检查您的环境。只允许使用单引号和双引号字符串。(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
我已经在互联网上挖掘了一个小时,但一无所获。有人见过类似 rollup-plugin-node-resolve 的解析器用于从 URL 解析模块吗?
我必须快速继续,所以最终只编写了汇总插件的框架。我仍然觉得解析绝对路径应该是rollup的核心功能。
更新的片段
我们已经使用它来为我们的几个应用程序转译生产代码已有相当长的一段时间了。
const fs = require('fs'),
path = require('path'),
axios = require("axios")
const createDir = path => !fs.existsSync(path) && fs.mkdirSync(path)
const mirrorDirectoryPaths = async ({ cacheLocation, url }) => {
createDir(cacheLocation)
const dirs = [], scriptPath = url.replace(/:\/\/|:/g, "-")
let currentDir = path.dirname(scriptPath)
while (currentDir !== '.') {
dirs.unshift(currentDir)
currentDir = path.dirname(currentDir)
}
dirs.forEach(d => createDir(`${cacheLocation}${d}`))
return `${cacheLocation}${scriptPath}`
}
const cacheIndex = {}
const writeToDiskCache = async ({ cacheLocation, url }) => {
//Write a file to the local disk cache for rollup to pick up.
//If the file is already existing use it instead of writing a new one.
const cached = cacheIndex[url]
if (cached) return cached
const cacheFile = await mirrorDirectoryPaths({ cacheLocation, url }),
data = (await axiosInstance.get(url).catch((e) => { console.log(url, e) })).data
fs.writeFileSync(cacheFile, data)
cacheIndex[url] = cacheFile
return cacheFile
}
const urlPlugin = (options = { cacheLocation }) => {
return {
async resolveId(importee, importer) {
//We importing from a URL
if (/^https?:\/\//.test(importee)) {
return await writeToDiskCache({ cacheLocation: options.cacheLocation, url: importee })
}
//We are importing from a file within the cacheLocation (originally from a URL) and need to continue the cache import chain.
if (importer && importer.startsWith(options.cacheLocation) && /^..?\//.test(importee)) {
const importerUrl = Object.keys(cacheIndex).find(key => cacheIndex[key] === importer),
importerPath = path.dirname(importerUrl),
importeeUrl = path.normalize(`${importerPath}/${importee}`).replace(":\\", "://").replace(/\\/g, "/")
return await writeToDiskCache({ cacheLocation: options.cacheLocation, url: importeeUrl })
}
}
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1923 次 |
| 最近记录: |