1. uniapp中使用import遇到的问题
在uniapp开发中,当我们想要使用ES6 import
语法来引入其他模块时,却发现会出现错误,比如:
Failed to resolve module specifier "xxx". Relative references must start with either "/", "./", or "../".
这是由于uniapp使用的是commonJS
规范而不是ES6的模块规范,所以不能直接使用import
关键字。
2. uniapp中使用require
代替import
为了解决这个问题,可以使用require
来代替import
。
2.1 安装babel-plugin-transform-commonjs
首先需要安装babel-plugin-transform-commonjs
:
npm install babel-plugin-transform-commonjs --save-dev
2.2 在.babelrc中添加配置
在项目根目录下,找到.babelrc
文件,添加以下配置:
{
"plugins": ["transform-commonjs"]
}
2.3 引入模块
在需要引入模块的文件中,使用require
代替import
来引入所需要的模块:
const module = require('module')
这样就可以在uniapp中使用require
来引入模块了。
3. 使用uni.requireModule
代替require
在uniapp中,还可以使用uni.requireModule
来代替require
,这样可以避免使用babel-plugin-transform-commonjs
插件。
3.1 引入模块
在需要引入模块的文件中,使用uni.requireModule
来引入所需要的模块:
const module = uni.requireModule('module')
其中,module
为需要引入的模块名。
3.2 特殊模块的引入
对于一些特殊的模块,比如vue-router
、vuex
等,需要使用uni.requireNativePlugin
来引入:
const router = uni.requireNativePlugin('uni-app-plus://router')
其中,uni-app-plus://router
为vue-router
的模块名。
4. 总结
使用import
在uniapp中引入模块会出现错误,我们可以使用require
代替import
,或者使用uni.requireModule
来引入模块。对于特殊的模块,需要使用uni.requireNativePlugin
来引入。