我正在嘗試捆綁我的應用程式的大約 10 多個 javascript 檔案,這些檔案作為腳本加載到index.html檔案中。它們根據彼此的依賴關系正確排序。
<script src="/js/main.js"></script>
<script src="/js/user.js"></script>
<script src="/js/contact.js"></script>
...
每個檔案中的代碼如下所示:
// main.js
const _main = {};
_main.MethodOne = function(){
...
}
// user.js
const _user = {};
_user.MethodTwo = function(){
// Can access the method from main.js file
_main.MethodOne();
}
// contact.js
const _contact = {};
_contact.MethodThree = function(){
// Can access the methods from main.js & user.js file
_user.MethodTwo();
_main.MethodOne();
}
現在,當通過 webpack 捆綁它們時,常量變數_main&_contact被_user重命名為一些隨機字母。但是,用于從其他檔案呼叫這些方法的名稱在每種情況下都保持不變,即_user.MethodTwo()不會_main.MethodOne()改變。
這是我的webpack.config.js
entry: {
vendors: [
'./public/js/colorpicker.js',
...
],
app: [
'./public/js/main.js',
'./public/js/user.js',
'./public/js/contact.js'
]
},
mode: 'production',
output: {
filename: 'js/[name].[contenthash].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
publicPath: 'auto',
assetModuleFilename: 'img/[hash][ext][query]'
},
我閱讀了 webpack 檔案,但是沒有得到任何關于這個問題的線索。
uj5u.com熱心網友回復:
您最好的選擇是通過使用匯入和匯出來遷移到模塊方法。
所以不是像你那樣定義全域變數,每個檔案都會匯出相應的變數。如果一個檔案需要另一個檔案中的變數,它只需要匯入它。
// main.js
export const _main = {};
_main.MethodOne = function(){
...
}
// user.js
import {_main} from "./main.js";
export const _user = {};
_user.MethodTwo = function(){
// Can access the method from main.js file
_main.MethodOne();
}
// contact.js
import {_main} from "./main.js";
import {_user} from "./user.js";
const _contact = {};
_contact.MethodThree = function(){
// Can access the methods from main.js & user.js file
_user.MethodTwo();
_main.MethodOne();
}
在此處閱讀有關匯入/匯出的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474853.html
