这篇文章给大家介绍使用webpack4怎么开发小程序,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
思路
对等编译输出小程序项目的所有文件(严格按照小程序需要的文件及目录结构输出)。js/wxs通过babel编译输出,wxml/json直接输出,wxss通过stylus编译输出(我们使用stylus开发样式),顺带使用webpack抽离公共模块文件common.js,并将runtime运行时抽离作为一个独立文件。这样既精简了代码,又享用到了webpack为我们带来的好处。嗯,看上去很简单嘛,实际上却是踩了不少的坑!脚上的茧老厚了~~~
webpack module配置
module: {
rules: [
{
test: /\.(wxml|axml)/, // 为支付宝小程序留了个伏笔,哈哈
use: [
relativeFileLoader(isWechat ? 'wxml' : 'axml'), // 这里使用file-loader简单封装了一下
'extract-loader',
'html-loader'
]
},
{
test: /\.(jp(e?)g|png|gif)$/,
use: relativeFileLoader()
},
{
test: /\.wxss$/,
include: SRC,
use: relativeFileLoader(),
},
{
test: /\.wxs$/,
include: SRC,
exclude: /node_modules/,
use: [
relativeFileLoader(),
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'es2015',
'stage-0'
]
},
}
]
},
{
test: /\.js$/,
use: {
loader: 'happypack/loader',
options: {
id: 'babel'
}
},
exclude: /node_modules/,
},
{
test: /\.styl$/,
include: SRC,
use: [
relativeFileLoader(isWechat ? 'wxss' : 'acss'),
'stylus-loader'
]
}
]
},
熟悉webpack的同学通过上面的moudle配置应该能够看出资源文件编译的思路,当然直接这样配置肯定做不到正确编译,还有一些坑需要踩
全文件entry
为了对等输出,我们需要把所有文件整理为entry给webpack处理,这样的好处是js能够使用npm包,所有文件都能够支持热更新机制(webpack的热更新响应非常快,gulp的热更新很难精细控制,当项目足够大的时候,响应很慢)
function entries(dir) {
var jsFiles = {}
let _partten = /[\/|\\][_](\w)+/;
let re_common = /(.*)\/common\//
const accessExts = ['.wxml', '.wxss', '.styl', '.wxs', '.json', '.png', '.jpg', '.jpeg', '.gif']
if (fse.existsSync(dir)) {
globby.sync([`${dir}/**/*`, `!${dir}/js/**/cloudfunctions`, '!node_modules', `!${dir}/dist`]).forEach(function (item) {
if (!re_common.test(item)) {
if (!_partten.test(item)) {
const fileObj = path.parse(item)
const xcxSrc = path.join(dir, 'js')
if (~item.indexOf(xcxSrc)) {
const fileStat = fs.statSync(item)
const relativeFile = item.replace(xcxSrc, '')
let relativeKey = relativeFile.replace(fileObj.ext, '').substring(1)
if (fileObj.ext == '.js') {
jsFiles[relativeKey] = item
}
else {
if (accessExts.indexOf(fileObj.ext) > -1) {
jsFiles['nobuild__' + relativeFile] = item
}
}
}
}
}
})
}
return jsFiles
}
上述是entry的生成代码,涵盖了小程序目录结构下的所有需要的文件,并加上了一些特定的标识,以便于后续文件编译输出
非JS文件的输出
在entry方法中我们将wxml,wxss等文件作为entry统统灌给webpack去处理,正常我们使用webpack时是不会把非js文件作为entry输给webpack的。你猜webpack会报错吗,----- 哈哈,报错就讲不下去了,webpack会傻傻的把每个entry文件都当做js来对待,并且正常输出,*.wxml.js,等等,这是什么鬼,我并不需要这样的东东。加个插件来处理一下
compiler.hooks.compilation.tap('wpConcatFile', (compilation, params) => {
compilation.hooks.beforeChunkAssets.tap('wpConcatFile', () => {
compilation.chunks = compilation.chunks.filter(function (item) {
return item.name.indexOf('nobuild__') == -1
})
})
...
...
}
nobuild__是在生成entry代码是给非js文件加上的prefix前缀,在插件中我们排除掉非js,将正常的js文件重新chunk,js文件就能够正常的输出了,那么那些非js文件呢?webpack并不会编译生成它们,中途它们就会被module中的xx-loader处理完,然后被file-loader给甩出去了。
全局变量替换
将全局变量替换为微信小程序的wx,我们通过插件解决
const globalVar = 'wx'
...
...
...
let contentObj = compilation.assets[file]
let code = contentObj.source()
code = code.replace(windowRegExp, that.globalVar);
contentObj = new RawSource(code)
compilation.assets[file] = new ConcatSource(
contentSource,
'\n',
'\/**auto import common&runtime js**\/',
'\n',
contentObj,
);
通过上述代码不难看出,我们读取了每个文件的源码,并将全局变量window/global替换为wx,再进行源码重组。
运行时文件引入
我们需要引入runtime.js和common.js文件,runtime运行环境是webpack为每个编译文件插入的用于解析define, require, module等等这些的文件引入方法,为了精简文件,我们将之抽离为runtime.js,common.js为我们抽离出来的公共模块文件。在web/h6下引入这些资源是不是so easy,但你还记得我们是在小程序环境下嘛,并不能通过<script>标签来引入资源文件啊啊啊,你会不会猛拍脑门,一下就慌了(哈哈)。老办法,我们通过插件解决
const lens = []
let posixPath = ''
const matchIt = chunk.name.match(/\//g)
if (matchIt) {
matchIt.forEach(it => lens.push(this.prePath))
// posixPath = './'+lens.join('')
posixPath = lens.join('')
} else {
posixPath = './'
}
let posixPathFile = posixPath + 'runtime.js'
let contentSource = this.contentSource.replace('~~~~', posixPathFile)
if (chunk.name.indexOf('runtime') > -1) {
posixPathFile = posixPath + 'common.js'
if (hasCommon) {
contentSource = this.contentSource.replace('~~~~', posixPathFile)
} else {
contentSource = ''
}
}
关于使用webpack4怎么开发小程序就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。