Unable to import module after bundling with web pa

2019-08-11 12:02发布

问题:

I have the following index.js code:

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

export default Asp;

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();

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" }
        ]
    }
};

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

UPDATE:

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()
    ]
}

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

回答1:

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.

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')
},

to be

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


回答2:

In index.js file, you just need to import Asp, and remove the export line. So the index.js file will be:

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

In run.js

import {Asp} from './dist/bundle.js'; 

const myASP = new Asp();