因为种种缘由,咱们选择了Ueditor做为咱们的富文本编辑器选型。javascript
Ueditor不支持模块化,因此没法在代码中使用import去引入。一开始咱们在项目中是将Ueditor的js文件直接经过script标签引入,在React的代码里直接使用window.UE去使用编辑器。可是这就有一个问题,咱们对UE的源码进行了改动,加入了定制化的功能。而直接引入的UE文件在浏览器是有缓存的,咱们每次改动都要清除缓存才能生效。html
咱们要解决缓存这个问题,webpack配置就必须知足如下条件:java
为了能让UE的文件进入打包流程,咱们将它做为一个新的入口文件react
const entry = {
main: ['babel-polyfill', './src/main.js'],
ueditor_config: ['./src/common/UEditor/ueditor.config.js'],
ueditor_all: ['./src/common/UEditor/ueditor.all.js']
};
new HtmlWebpackPlugin({
template: `./src/app/${key}/templates/${filename}`,
filename: `../view/${targetHtml}`,
hash: true,
chunks: [ueditor_all, ueditor_config, main]
})
复制代码
按上面的配置构建完成以后,会发现效果并非咱们想要的webpack
<script type="text/javascript" src="/public/main.xxxx.js"></script>
<script type="text/javascript" src="/public/ueditor.config.xxxx.js"></script>
<script type="text/javascript" src="/public/ueditor.all.xxxx.js"></script>
复制代码
main.js在UE的前面,这样main中使用window.UE就会报错。显然,咱们须要一种方式来让这个顺序符合咱们的预期。web
HtmlWebpackPlugin的chunksSortMode属性是用来控制插入模板html的script标签的顺序的,默认是auto,会根据webpack给每一个chunk生成的id去排序,在entry中排的越前的,id就越小,那在html中就排在前面。因此这里咱们第一种解决方案是,调换一下entry顺序浏览器
const entry = {
ueditor_config: ['./src/common/UEditor/ueditor.config.js'],
ueditor_all: ['./src/common/UEditor/ueditor.all.js']
main: ['babel-polyfill', './src/main.js']
};
复制代码
可是这个方法有缺陷,当项目中有多个模板html须要引用入口的时候,在entry里面去控制这个排序就会遇到冲突的状况,不够灵活。 因此咱们把顺序的控制权下方到每一个HtmlWebpackPlugin中,经过把chunksSortMode设置为manual,按chunks的顺序去排序,例如缓存
new HtmlWebpackPlugin({
...
chunks: [ueditor_config, ueditor_all, main]
})
复制代码
这样,生成的html中srcipt就会是下面的顺序bash
<script type="text/javascript" src="/public/ueditor.config.xxxx.js"></script>
<script type="text/javascript" src="/public/ueditor.all.xxxx.js"></script>
<script type="text/javascript" src="/public/main.xxxx.js"></script>
复制代码
如今看上去顺序是ok了,可是运行的时候,咱们发现控制台报错 regeneratorRuntime is not definedbabel
第二步最后出现的错误,是咱们使用的ES6新API没有被转换致使的。因为以前咱们只是在main的入口加了babel-polyfill,而main又是在UE的后面加载的,因此致使了报错。因此须要将babel-polyfill放到入口第一个文件
const entry = {
ueditor_config: ['babel-polyfill', './src/common/UEditor/ueditor.config.js'],
ueditor_all: ['./src/common/UEditor/ueditor.all.js']
main: ['./src/main.js']
};
复制代码
继续运行后,第二步的错误已经解决了。不过,新的错误又出现了
TypeError: 'caller', 'callee', and 'arguments'
properties may not be accessed on strict mode functions or the arguments objects for calls to them
复制代码
bable会默认给编译的js加上use strict; 严格模式下caller、callee 和arguments 是不能使用的,追溯到UE的源码中,咱们发现里面大量使用了arguments.callee这种写法。 直接把源码都改了不现实,因此只能经过配置让bable忽略这个文件。在.babel中咱们加入以下配置,
"presets": [
"react"
],
"ignore": [
"./src/common/UEditor/ueditor.all.js"
],
复制代码
到此webpack就能按照咱们的预期构建UE模块了。