2017-06-09 41 views
0

我正在使用JS在我的Web應用程序中實現各種功能。 到目前爲止,我使用了一個文件(main.js),這個文件變得非常大和凌亂。我想將這個文件「拆分」爲幾個文件(例如a.js,b.jsc.js),然後將它們導入到main.js。這樣我的發展將是整潔和乾淨的,在html方面,我只需要引用一個js文件。將JavaScript文件拆分爲幾個文件

有沒有更好的方法來做到這一點,比使用import和export語句?

是否有像SASS中的某種「預處理器」,它將_partialA.scss,_partialB.scss,_partialC.scss合併到main.scss中?

感謝您的幫助!

回答

0

我對webpack並不完全滿意,所以我寫了自己的小腳本。隨意使用它。

將做到以下幾點:

  • 觀看源路徑定義的文件夾。
  • 如果它檢測到任何在源文件夾中的文件的變化,將讀取的所有文件源文件夾 ,並將其寫入到文件destination.js

要執行,只要執行節點腳本名。 js

/* jshint esversion: 6 */ 
'use strict'; 

const watch = require('node-watch'); 
let allFilesPath = []; 
const pathDestination = './path/to/destination.js'; 
const source = 'source/folder/'; 

const fs = require('fs'); 
init(); 

function init() { 
    fs.truncate(pathDestination, 0, function() { 
     console.log('delete everything in', pathDestination); 
    }); 

    const allFiles = fs.readdirSync(source); 
    allFiles.forEach(function(element) { 
     allFilesPath.push(source + element); 
    }); 
    allFiles.forEach(function(element) { 
     getFileContent(element); 
    }); 
} 

function getFileContent(file) { 
    fs.readFile(source + file, 'utf8', function(err, data) { 
     if (err) { 
      return console.log(err); 
     } else { 
      console.log(source + file + ' was added to ' + pathDestination); 
      addToBundle(data); 
     } 
    }); 
} 

function addToBundle(code) { 
    fs.appendFile(pathDestination, code, function(err) { 
     if (err) { 
      console.log(err); 
     } 
    }); 
} 

watch(allFilesPath, function(evt, filename) { 
    console.log(filename, 'changed'); 
    init(); 
    console.log(); 
}); 
0

您可以使用ES6導入並使用webpack捆綁您的代碼。

+0

這看起來很有趣。讓我深入瞭解這一點 – User12547645