使用require.ensure按需加载无效

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="aBtn">A按钮</div>
<div id="bBtn">B添加</div>

<script src="dist/index.min.js"></script>

</body>
</html>
import _ from 'lodash';

function component() {
    var element = document.createElement('div');

    // Lodash, currently included via a script, is required for this line to work
    // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    return element;
}

document.getElementById("aBtn").onclick = function() {

    require.ensure([], function() {
        var awork = require('../js/first.js')

        //异步里面再导入同步模块--实际是使用同步中的模块
    })
}

document.getElementById("bBtn").onclick = function() {

    require.ensure([], function() {
        var bwork = require('../js/second.js')

    })
}

document.body.appendChild(component());

first.js

console.log('***** 我是第一名 *****');

second.js

console.log('***** 第二个开始 *****');

webpack.common.js

const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

const config = {
    entry: {
        "index": "./src/index.js"
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        //filename: 'bundle.js'
        //filename: "[name].js"
        filename: "[name].min.js", // 对应entry里面 生成出来的文件名
        chunkFilename: "[name].min.js" // 按需加载(异步)模块时候,这时生成的文件名 以chunkname配置的

    },
    module: {

    },
    plugins: [

    ]
};

module.exports = config;

图片描述
图片描述

阅读 3.5k
1 个回答

可以看这里,推荐使用下面的import方式。require.ensure是老式写法。

function getComponent() {
  // 这个注释是必要的,根据配置生成的chunk name是lodash.chunk.js,移除注释会变成[id].chunk.js
  // 而且生成的chunk会在header标签中被引入
  return import(/* webpackChunkName: "lodash" */ 'lodash')
  .then(_ => {
    const element = document.createElement('div');
    element.innerHTML = _.join(['Hello', 'webpack!'], ' ');
    return element;
  })
  .catch(error => 'An error occurred while loading the component');
}  
 

getComponent().then(element => {
  document.body.appendChild(element);
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题