由文件依赖关系输出加载排序

题目

// 3. 由文件依赖关系输出加载排序
function sortDeps(fileMaps) {
}

sortDeps({ 'index.js': ['1.js', '2.js'], '2.js': ['1.js']});
// output: [ '1.js', '2.js', 'index.js' ]
// index.js 依赖 1.js 2.js
// 2.js 依赖 1.js
// 因此正确的加载顺序是 1.js 2.js index.js

题解

function sortDeps(fileMaps) {
    return Object.keys(fileMaps).reduce((result,itemKey) => {
        const itemDeps = fileMaps[itemKey]

        // 看看结果列表中有没有当前的文件
        // 如果有 要将当前文件的依赖插入当前文件前面
        // 如果没有 直接依次放入当前文件的依赖、当前文件
        let itemIndex = result.findIndex((item) => item = itemKey)
        if(itemIndex !== -1){
            itemDeps.map(itemDep => {
                // 后来的依赖可能已经存在了,需要去重
                if(!result.includes(itemDep)){
                    result.splice(itemIndex,0,itemDep)
                    itemIndex++
                }
            })

        }else{
            result.push(...itemDeps,itemKey)
        }

        return result

    },[])
}

console.log(sortDeps({ 'index.js': ['1.js', '2.js'], '2.js': ['1.js']}))
console.log(sortDeps({ 'index.js': ['1.js', '2.js'], '2.js': ['1.js'],'1.js':['3.js','4.js']}))

// output: [ '1.js', '2.js', 'index.js' ]
// index.js 依赖 1.js 2.js
// 2.js 依赖 1.js
// 因此正确的加载顺序是 1.js 2.js index.js

”被依赖的一定是放前面的,所以会是1,2,index,1,2 然后针对这个从后往前去重,前面有的就把后面的删了
或者说,先把第一个拿出来1,2,index,然后从后面每一个的被依赖、依赖这样的顺序去取,取到了看看有没有,没有的话就插入到依赖的前面去,有的话就不放了“

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 打包输出公共 JS 加载文件可以通过配置 `webpack` 实现。 首先,在 `webpack.base.conf.js` 中添加 `CommonsChunkPlugin` 插件,将公共的代码提取到一个 `vendor` chunk 中: ```javascript const webpack = require('webpack') module.exports = { // ...其他配置 plugins: [ // 提取公共代码 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // 任何引用 node_modules 中的模块都被视为外部模块 return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }) ] } ``` 然后,在 `webpack.prod.conf.js` 中,使用 `HtmlWebpackPlugin` 插件将 `vendor` chunk 添加到生成的 HTML 文件中: ```javascript const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { // ...其他配置 plugins: [ // 生成 HTML 文件,并注入静态资源 new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, chunksSortMode: 'dependency' }) ] } ``` 其中 `chunksSortMode` 选项指定 chunk 的排序方式,`'dependency'` 表示按依赖关系排序,这样可以确保 `vendor` chunk 在其他 chunk 之前加载。 最后,打包生成的静态资源文件中,将会有一个名为 `vendor.js` 的文件,它包含了所有来自 `node_modules` 目录下的第三方依赖库。在 HTML 文件中添加: ```html <script src="static/js/vendor.js"></script> ``` 即可加载这个公共的 JS 加载文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值