我创建了一个新的 Cordova 应用程序
cordova create MyApp
Run Code Online (Sandbox Code Playgroud)
我想使用几个 Web 库(不依赖于 node.js),所以我用 npm 安装了它们。例如
npm install onsenui vue-onsenui --save-dev
Run Code Online (Sandbox Code Playgroud)
目录结构如下所示:
config.xml
hooks/
node_modules/
package.json
platforms/
plugins/
res/
www/
Run Code Online (Sandbox Code Playgroud)
www 中的 index.html 文件具有包含库的脚本标签
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="onsenui.js"></script>
<script type="text/javascript" src="vue-onsenui.js"></script>
Run Code Online (Sandbox Code Playgroud)
运行该cordova run browser命令时,Web 服务器运行良好并按原样显示页面,包括加载 cordova.js 文件,但它为其他库返回 404。
有没有办法在 Cordova 中使用这些节点模块而不将它们复制到 www 目录中?
使用 npm 包:cordova-import-npm
您可以在 before ,即文件组装进行编译时使用钩子。cordova prepare
config.xml并添加此行(不在任何平台内,而是在根目录中,即在内部<widget):<hook src="hooks/importNpmPackages.js" type="before_prepare"/>
Run Code Online (Sandbox Code Playgroud)
hooks/importNpmPackages.js创建包含此内容的文件const fse = require('fs-extra')
const path = require('path')
const twoSpaces = ' ' // for log indentation
var projectRoot
module.exports = function (context) {
console.log(`${context.hook} : ${path.relative(context.opts.projectRoot, context.scriptLocation)}`)
projectRoot = context.opts.projectRoot
console.log(twoSpaces + 'Project root directory: ' + projectRoot)
copyFile('jquery', path.join('dist', 'jquery.min.js'), path.join('js', 'res', 'jquery.min.js'))
copyFile('bootstrap', path.join('dist', 'js', 'bootstrap.min.js'), path.join('js', 'res', 'bootstrap.min.js'))
copyFile('bootstrap', path.join('dist', 'css', 'bootstrap.min.css'), path.join('css', 'res', 'bootstrap.min.css'))
}
function copyFile (npmPackage, // oficial name of the npm package from which the file is to be copied from
fileRelativePath, // file path with respect to the main directory of the npm package (node_modules/<package>/)
destFilePath) { // file's path to where it is copied, relative to the project www/ directory
const packageDirFullpath = path.dirname(require.resolve(path.join(npmPackage, 'package.json')))
const fileOriginFullPath = path.join(packageDirFullpath, fileRelativePath)
const fileDestFullPath = path.join(projectRoot, 'www', destFilePath)
fse.copySync(fileOriginFullPath, fileDestFullPath)
const consoleMsg = npmPackage + ': ' +
path.relative(projectRoot, fileOriginFullPath) + ' -> ' +
path.relative(projectRoot, fileDestFullPath)
console.log(twoSpaces + consoleMsg)
}
Run Code Online (Sandbox Code Playgroud)
正如您在此文件中看到的,我正在使用具有以下语法的函数复制 jquery 和 bootsrap 文件copyFile:
copyFile(
'<npmPackageName>',
'<path/of/originFile/relative/to/packageDir>',
'<path/to/destFile/relative/to/wwwDir>'
)
Run Code Online (Sandbox Code Playgroud)
我在所有科尔多瓦项目中都使用了它,它就像一个魅力。我就是这么看的
钩子也会被触发,cordova build因为cordova build等于cordova prepare && cordova compile。
| 归档时间: |
|
| 查看次数: |
5043 次 |
| 最近记录: |