与Web Pack捆绑后无法导入模块 [英] Unable to import module after bundling with web pack

查看:220
本文介绍了与Web Pack捆绑后无法导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下index.js代码:

I have the following index.js code:

import {Asp} from './src/asp.js';

export default Asp;

以及以下run.js代码:

and the following run.js code:

import Asp from './dist/bundle.js'; // Uncaught SyntaxError: The requested module does not provide an export named 'default'
import Asp from './index.js'; // works

const myASP = new Asp();

和webpack(3.11)配置文件:

and webpack (3.11) config file:

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
        ]
    }
};

我不知道为什么在导入...帮助...时使用bundle.js不起作用...

I can't figure out why using the bundle.js doesn't work when I import...help...

更新:

我放弃了webpack,并通过以下配置解决了我的问题:

I gave up on webpack and moved to rollup with the following configuration which solved my problem:

import uglify from 'rollup-plugin-uglify';

export default {
    input: 'src/index.js',
    output:{
        file: 'dist/index.js',
        name: 'Asp',
        format: 'es'
    },
    plugins: [
        uglify()
    ]
}

我不知道在webpack中有什么等效的方法-但这确实起作用了!

I couldn't figure out what was the equivalent to this in webpack - but it did the job!

推荐答案

默认情况下,Webpack输出一个脚本文件,这意味着它没有导出,因此尝试将其导入到另一个文件中不会产生任何结果.

By default Webpack outputs a Script file, meaning that it has no exports, so trying to import it into another file will not yield any results.

要告诉Webpack将捆绑软件输出为可重用的库,您需要告诉它使用 output.libraryTarget ,因此您可能需要调整

To tell Webpack to output the bundle as a reusable library, you need to tell it to do that with the output.libraryTarget, so in your case you likely want to adjust

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
},

成为

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'commonjs2'
},

这篇关于与Web Pack捆绑后无法导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆