[英]Are module imports treated differently by vite in development and production?
我正在嘗試將庫(jointjs)導入 Vue 應用程序。 它被分配為 Vue 上的全局屬性並隨后被修改。 這是我正在嘗試做的簡單復制:
import Vue from 'vue';
import * as joint from 'jointjs';
import App from '@/App.vue';
// we need to get our own connectors
let customConnectors={
f: function() {}
}
Vue.use({
install: function (Vue) {
// In development, this works:
// _.assign(joint.connectors, customConnectors);
// as does this:
// _.each(customConnectors, (item, key) => { joint.connectors[key] = item;});
// and this:
// for (const connector in customConnectors) {
// joint.connectors[connector] = customConnectors[connector];
// }
// but none of those work in production, saying joint is a constant or not extensible
// this one gives a build error about f not being exported by jointjs/src/connectors
// joint.connectors['f'] = customConnectors['f'];
// this one gives the same error but runs without error; but only when minified, so I think it's actually
// just removing the statement
joint.connectors.f = customConnectors.f;
Vue.joint = joint;
}
});
let app = new Vue({
joint,
render: h => h(App)
}).$mount('#app');
感謝 Estus Flask 在評論中的提示,我已經成功地完成了這項工作。
我首先使用 rollup 將 Jointjs 轉換為 ES 模塊。
npm i --save-dev rollup-plugin-commonjs
Rollup 應該已經安裝了,因為 vite 使用它。
我在項目根目錄中創建了一個 rollup.config.js 文件:
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'node_modules/jointjs/joint.mjs',
output: {
file: 'src/plugins/jointjsESM.js',
format: 'es',
freeze: false, // this is key to preventing everything from being constant
},
plugins: [
commonjs({
// search for files other than .js files (must already
// be transpiled by a previous plugin!)
extensions: [ '.js', '.mjs' ], // Default: [ '.js' ]
// if true then uses of `global` won't be dealt with by this plugin
ignoreGlobal: false, // Default: false
// if false then skip sourceMap generation for CommonJS modules
sourceMap: false, // Default: true
}),
],
};
output.file
值可以指向您希望生成的模塊所在的任何位置。
然后,您可以創建 package.json 腳本(或使用 npx)來運行rollup --config rollup.config.js
這將在 output.file 位置創建新的模塊文件。 作為構建管道的一部分,您可以在 vite 構建之前運行此腳本。
然后,不是import * as joint from 'jointjs'
,而是從輸出的文件中導入,但你需要使用你需要的任何部分自己組裝關節對象......例如:
import {
g,
dia,
shapes,
connectors,
} from '@/plugins/jointjsESM.js';
let joint = { g, dia, shapes, connectors};
您還可以將jointjs 移動為僅作為開發依賴項安裝,因為它不被用作構建的一部分。
非常感謝多夫。 Idle-vue 包也有同樣的問題。 我花了幾天時間找到解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.