因爲種種緣由,咱們選擇了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模塊了。