Set correct path to lazy-load component using Webpack - ES6

a 夏天 提交于 2021-02-08 08:32:04

问题


In my app.js file I have the following event inside a function where I import another module (same as in the docs) using the lazy-loading technique:

button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
    var print = module.default;

    print();
});

And in my webpack config I set up this (besides Babel, SASS loaders, etc):

const path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
watch: true,
entry: {
    main: ['babel-polyfill', './src/js/app.js','./src/sass/main.sass']
},
output: {
    chunkFilename: '[name].bundle.js',
    path: path.resolve(__dirname, "dist"),
    filename: '[name].js',

},
module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ["babel-preset-env", "babel-preset-stage-0"]
                }
            }
        },
        {
            test: /\.sass$/,
            exclude: /node_modules/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                    'css-loader',
                    {
                        loader: 'sass-loader',
                        query: {
                            sourceMap: false,
                        },
                    },
                ],
            }),
        },
    ]
  }    
}

The problem is the path "./print" is from my "src" folder and not from my "dist" folder, where webpack puts all the bundles, so I get a 404 error. If I change the path to "./dist/print" then the webpack build will crash.

Am I missing a webpack configuration?

Edit: Folder structure:

src 
    js
        app.js
        print.js
dist
    main.bundle.js
    print.bundle.js

回答1:


You don't have to treat with the modules path in dist folder, only in src folder.

There is two solutions I think :

1/ Specify src path in your import statement :

button.onclick = e => import(/* webpackChunkName: "print" */ './src/js/print').then(module => {
    var print = module.default;

    print();
});

2/ Personally, What I usually do is to add src folder to resolved paths in config file:

resolve: {
    modules: [
      path.resolve('./node_modules'),
      path.resolve('./src/js')
    ],
    extensions: ['.json', '.js']
  },

Your code should then work without changing a line.



来源:https://stackoverflow.com/questions/50347293/set-correct-path-to-lazy-load-component-using-webpack-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!