将 Requirejs 和基于 Backbone 的应用程序迁移到 WebPack

2024-01-10

我有一个使用 Backbone.js 和 Marionette 与 Requirejs 开发的大型应用程序。我们使用 Grunt 进行构建。我需要将 Requirejs 迁移到 Webpack,因为我们经常看到模块加载超时。我觉得 Webpack 的多入口点方法比使用 Requirejs 将单页面转换为多页面更好。

总的来说,我们有大约 400 个 js 文件和 250 个 html[部分] 文件。项目结构是

app
    |--modules
    |     |-- module-A
    |        |- model
    |        |- collection         
    |        |- view
    |        |- module_utils
    |     |-- module-B
    |
    |---templates  
      |-- module-A
         |- view-1.html
         |- view-2.html         
      |-- module-B

requirejs 配置文件如下所示:

require.config({
    paths: {
        templates: "./../templates",
        jquery: "/static/lib/jquery/jquery.min",
        jquerymigrate: "/static/lib/jquery/jquery-migrate.min",
        jqueryui: "/static/lib/jqueryui/ui/minified/jquery-ui.custom.min",
        bootstrap: "/static/lib/bootstrap-3.1.1/dist/js/bootstrap",
        ...

    },

    shim: {
        'jquerymigrate': ['jquery'],
        'jquerybackstretch': ['jquery'],
        'jqueryuniform': ['jquery'],
        'jqueryui': ['jquery','jquerymigrate'],
        'bootstrap': ['jquery'],
        ....
        }
    }
})

这里 /static 指向我们在 nginx 配置中指定的位置,以提供 css、js 等内容。

为了将其转换为 webpack 配置,我从 webpack 配置文件开始,首先创建单个文件。而不是从多次入境开始。

var webpack = require("webpack");
var path = require("path");

module.exports = {
    entry: "./app.js",  
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    resolve: {
        alias: {
            "templates": "./../templates",
            "jquery": "../../lib/jquery/jquery.min",
            "jquerymigrate": "./..//lib/jquery/jquery-migrate.min",
            "jqueryui": "../../lib/jqueryui/ui/minified/jquery-ui.custom.min",
            "bootstrap": "../../lib/bootstrap-3.1.1/dist/js/bootstrap",
            "moment": "../../lib/moment/min/moment.min",
            ....

        } ,
        extensions: ['', '.js'],
        modulesDirectories: [ __dirname],
        root: [path.resolve('./../app/modules/')]

    }
}

function escapeRegExpString(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }
function pathToRegExp(p) { return new RegExp("^" + escapeRegExpString(p)); }

在我基于 requirejs 的应用程序中,模块的指定方式如下

define([
  'underscore', 
  'backbone',
  'utils',
  'core/constants',
  'text!templates/common/popup-template.html'
], function(_, Backbone, Utils, Constants, template) {

...
....
}

当我运行 webpack 时,出现错误“无法解析模块 templates/common/popup-template.html ”。然而,这个 html 是 Backbone 视图用来创建视图的部分 html/模板。

在其中一个网站中,我看到我需要 html-loader 插件。然后在 webpack 配置“text”:“html”中设置别名。并将“text!templates/common/popup-template.html”等行更改为“[精确路径]/templates/common/popup-template.html”。这意味着我需要更改大量代码。

对于这种迁移有更好的方法吗?

谢谢 普拉迪普


你需要text-loader插件,而不是“html”。您也不需要在 config 中编写任何内容。字首text-loader!依赖将附加它。

你试一试npm install text-loader --save-dev

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Requirejs 和基于 Backbone 的应用程序迁移到 WebPack 的相关文章

随机推荐