使用汇总

时间:2018-08-21 06:50:24

标签: es6-modules rollupjs

从ES6模块内的URL导入是完全有效的,因此我一直在使用这种技术在位于不同主机/端口上的微服务之间重用模块:

import { authInstance } from "http://auth-microservice/js/authInstance.js"

我正处于发布周期,并且已经开始了我通常使用汇总捆绑到IIFE的途径。汇总似乎不支持从URL导入es6模块,我认为应该这样做,因为规范:(

  

模块名称   要从中导入的模块。这通常是包含模块的.js文件的相对或绝对路径名。某些捆绑软件可能允许或要求使用扩展名;检查您的环境。只允许使用单引号和双引号字符串。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

我已经在互连网上挖了一个小时,却一无所获。有人看到过类似于rollup-plugin-node-resolve的解析器,用于从URL解析模块吗?

2 个答案:

答案 0 :(得分:1)

我不得不快速地继续前进,所以最终只写了一个汇总插件的框架。我仍然认为解析绝对路径应该是汇总的核心功能。

const fs = require("fs"),
    path = require('path'),
    axios = require("axios"),
    promisify = require("util").promisify,
    writeFile = promisify(fs.writeFile)

const cacheIndex = {}
const writeToDiskCache = async ({ cacheLocation, url }) => {
    const cached = cacheIndex[url]
    if (cached) return cached    

    const data = (await axios.get(url).catch((e) => { })).data,
        cacheFileName = `${path.basename(path.dirname(path.dirname(url)))}-${path.basename(path.dirname(url))}-${path.basename(url)}`,
        cacheFilePath = `${cacheLocation}${cacheFileName}`
    await writeFile(cacheFilePath, data)
    cacheIndex[url] = cacheFilePath

    return cacheFilePath
}
const urlPlugin = (options = {cacheLocation: "public/httpcache/"}) => {
    return {
        async resolveId(importee, importer) {
            if (/https?:\/\//.test(importee)) {
                return await writeToDiskCache({ cacheLocation: options.cacheLocation, url: importee})
            }
            if (importer && importer.startsWith(options.cacheLocation)) {
                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})
            }
        }
    }
}

答案 1 :(得分:0)

这个插件和以下配置对我有用: https://github.com/mjackson/rollup-plugin-url-resolve

import typescript from "@rollup/plugin-typescript";
import urlResolve from "rollup-plugin-url-resolve";

export default {
  output: {
    format: "esm",
  },
  plugins: [
    typescript({ lib: ["es5", "es6", "dom"], target: "es5" }),
    urlResolve(),
  ],
};

你显然可以删除 TypeScript 插件。