我开始评估JavaScript的模块工具,如RequireJS JavaScript的模块化。 这似乎是有用的,特别是在开发过程中,所以我并不需要所有的JS文件编译成mylib-<version>.js
每当我改变依赖文件之一。
我的应用程序分发与HTML和JavaScript文件,并在生产,我想使用的JavaScript文件的编译版本。
所以在发展,我的HTML文件可能看起来像
<html>
<head>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
</html>
但在生产中,我希望它看起来更像
<html>
<head>
<script src="mylib-1.0.js"></script>
</head>
</html>
我不认为它的生产应该有任何需要引用requirejs如果我分发编译的文件。
有没有办法做到这一点,而无需手动更改我的HTML文件之前,我分发应用程序?
RequireJs有一个优化的工具 ,它可以帮助你来缩小并连接的模块。 它有很多的选项,可能很难使用,但它可以与像一个构建工具更容易GruntJs或(尤其是) 约曼 ,它使用GruntJs建设。
在这两种可以使用rjs
任务(可优化模块),但再次约曼是一个更容易一点,因为它有发电机,将已经配置它为您提供:
// usemin handler should point to the file containing
// the usemin blocks to be parsed
'usemin-handler': {
html: 'index.html'
},
// rjs configuration. You don't necessarily need to specify the typical
// `path` configuration, the rjs task will parse these values from your
// main module, using http://requirejs.org/docs/optimization.html#mainConfigFile
//
// name / out / mainConfig file should be used. You can let it blank if
// you're using usemin-handler to parse rjs config from markup (default
// setup)
rjs: {
// no minification, is done by the min task
optimize: 'none',
baseUrl: './scripts',
wrap: true,
name: 'main'
},
在index.html
,你只需要使用一个注释行指定哪个JS文件应该被精缩/串接到输出文件:
<!-- build:js scripts/amd-app.js -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
<!-- endbuild -->
在上面的例子中,模块将被级联到一个文件,命名为amd-app.js
。
编辑:
这将通过执行来完成grunt
命令行。 这将启动很多有用的任务,这将在构建项目dist
文件夹,但这又是非常适应。
产生的index.html
文件( dist
)只(如果你想)一个JavaScript文件:
<script src="scripts/15964141.amd-app.js"></script>
我的建议是:使用约曼让生活更容易(至少在处理缩小/级联)。
首先,你必须使用编译您depency树成一个文件[R编译器 。 之后,你可以将条纹向下AMD装载机像杏仁 。 至少你必须找到一种方法来更改URL在索引HTML。
看看gruntjs它可以使自动化整个事情,有一堆任务喜欢usemin ,帮助您与过程。