如何通过rollupjs动态导入名称由参数定义的模块?

问题描述 投票:1回答:1

src / dynamicImport.js


export default function dynamicImport(path) {
    const parts = path.split('/');
    // 去掉后缀.js
    const namespace = parts.pop().replace(/\.\w+$/, '');
    let mid = '';

    if (parts.length) {
        mid = `${parts.join('/')}/`;
    }

    return new Promise((resolve, reject) => {
        console.log(mid, namespace)
        import(
            `@src/${mid}` + namespace + '.js'
        )
            .then(module => {
                resolve(module);
            })
            .catch(err => {
                reject(err);
            });
    });
}

src / index.js

dynamicImport('lib/test').then(({ default: test}) => {
    test();
})

src / lib / test.js

export default function test() {}

rollup.config.js

const rollup = require('rollup');
const babel = require('rollup-plugin-babel')
const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const alias = require('@rollup/plugin-alias')
const { uglify } = require('rollup-plugin-uglify')
const postcss = require('rollup-plugin-postcss')
const replace = require('@rollup/plugin-replace')
const path = require('path');
const getBabelConfig = require('./getBabelCommonConfig.js');

const dirs = {
    src: path.resolve(__dirname, '../src'),
    dist: path.resolve(__dirname, '../dist'),
}



const getInputOptions = (isDev, isMinify) => {
    const babelConfig = getBabelConfig(false);
    babelConfig.runtimeHelpers = true;
    const inputOptions = {
        input: path.resolve(dirs.src, 'index.js'),
        plugins: [
            replace({
                'process.env.NODE_ENV': isDev ? 'development' : 'production'
            }),
            postcss({
                extensions: ['.css', '.less'],
                extract: true,
                modules: true,
                minimize: isMinify
            }),
            alias({
                resolve: ["",".js"],
                entries: {
                    '@lib': path.resolve(__dirname, '../src/lib'),
                    '@src': path.resolve(__dirname, '../src')
                }
            }),
            resolve({
                extensions: ["",".js"],
            }),
            commonjs({
                include: /node_modules/
            }),
            babel({
                ...babelConfig,
                extensions: [".js"]
            })
        ]
    };

    if (isMinify) {
        inputOptions.plugins.push(uglify());
    }

    return inputOptions;
}

const getOutputOptions = (isMinify) => {
    return {
        format: 'umd',
        file: path.resolve(dirs.dist, isMinify ? 'index.min.js' : 'index.js'),
        name: 'test1',
        sourcemap: true
    }
}

const compile = async () => {
    const inputOptions = getInputOptions(true, false);
    const bundle = await rollup.rollup(inputOptions);
    const outputOptions = getOutputOptions(false);
    await bundle.generate(outputOptions);
    await bundle.write(outputOptions);
}


const build = async () => {
    const inputOptions = getInputOptions(true, true);
    const bundle = await rollup.rollup(inputOptions);
    const outputOptions = getOutputOptions(true);
    await bundle.generate(outputOptions);
    await bundle.write(outputOptions);

}


const watch = () => {
    const watchOptions = {
        ...getInputOptions(true),
        output: [getOutputOptions()],
        watch: {
            exclude: 'node_modules/**'
        }
    };

    const watcher = rollup.watch(watchOptions);

    watcher.on('event', event => {
        // event.code can be one of:
        //   START        — the watcher is (re)starting
        //   BUNDLE_START — building an individual bundle
        //   BUNDLE_END   — finished building a bundle
        //   END          — finished building all bundles
        //   ERROR        — encountered an error while bundling
        //   FATAL        — encountered an unrecoverable error
    });
}

const isDevelopment = ['NODE_DEV', 'BROWSER_DEV'].indexOf(process.env.NODE_ENV) >= 0;

if (isDevelopment) {
    watch(true);
} else {
    compile();
    build();
}

这不是在dist中创建的大块js。仅构建index.js。使用rollup.js构建代码时,这没有错误。

/ dist / index.js

(function (factory) {
    typeof define === 'function' && define.amd ? define(factory) :
    factory();
}((function () { 'use strict';

    function dynamicImport(path) {
      var parts = path.split('/'); // 去掉后缀.js

      var namespace = parts.pop().replace(/\.\w+$/, '');
      var mid = '';

      if (parts.length) {
        mid = "".concat(parts.join('/'), "/");
      }

      return new Promise(function (resolve, reject) {
        console.log(mid, namespace);
        import("@src/".concat(mid) + namespace + '.js').then(function (module) {
          resolve(module);
        }).catch(function (err) {
          reject(err);
        });
      });
    }

    dynamicImport('lib/test').then(function (_ref) {
      var test = _ref.default;
      test();
    });

})));
//# sourceMappingURL=index.js.map

============================================>

在webpack中,我可以像这样动态导入模块:

import(
    /* webpackChunkName: "[request]" */
    `@src/${mid}` + namespace
 ).then()

我该如何使用汇总。我需要使用参数传递模块名称。

src / dynamicImport.js导出默认函数dynamicImport(path){const parts = path.split('/'); //去掉后缀.js const名称空间= parts.pop()。replace(/ \。\ w + $ /,'');让mid ='';如果...

webpack rollup rollupjs dynamic-import
1个回答
1
投票
© www.soinside.com 2019 - 2024. All rights reserved.