简体   繁体   English

如何使用 Webpack 包含/导入整个 JS 文件

[英]How to include/import an entire JS file with Webpack

I am new to Webpack, but I have a habit of building my web apps in the following manner:我是 Webpack 的新手,但我习惯于按以下方式构建我的 web 应用程序:

  1. Declare a global variable for the project.为项目声明一个全局变量。
  2. Create several JS files that use the global variable to declare functions and variables创建几个使用全局变量声明函数和变量的JS文件
  3. Link these separate js files in the HTML file, and combine them when going to production.在 HTML 文件中链接这些单独的 js 文件,并在生产时将它们组合起来。

For example my first JS file would be "init.js":例如我的第一个 JS 文件是“init.js”:

let FP = {}; // Global Object

My second would be "processing.js":我的第二个是“processing.js”:

FP.addNumbers = function(a, b){
  return a+b;
}

The HTML would include: HTML 将包括:

 <script src="init.js"></script> 
 <script src="processing.js"></script> 

Then in production I use a node plugin I wrote to parse the HTML page and combine all the JS files into one.然后在生产中我使用我编写的节点插件来解析 HTML 页面并将所有 JS 文件合并为一个。

I want to do something similar with Webpack, but the only way I found to combine files is with "include".我想对 Webpack 做一些类似的事情,但我发现合并文件的唯一方法是使用“include”。 Which requires each file use a separate variable name.这需要每个文件使用一个单独的变量名。

I literally just want to dump the contents of my separate JS files into init.js.我真的只是想将我单独的 JS 文件的内容转储到 init.js 中。 Is there a way to do this?有没有办法做到这一点?

If you're going to use Webpack to bundle your code, the right approach to something like this would be to take advantage of modular imports and exports to coordinate data between modules, otherwise the use of Webpack isn't really doing anything for you.如果你打算使用 Webpack 来捆绑你的代码,那么正确的方法是利用模块化导入和导出来协调模块之间的数据,否则使用 Webpack 对你没有任何帮助。

For example, here, try the following:例如,在这里,尝试以下操作:

// index.js
import { addFns } from './addFns.js';

const FP = {};
window.FP = FP; // use this if the object needs to be global
addFns(FP);
// addFns.js
export const addFns = (FP) => {
  FP.addNumbers = function(a, b){
    return a+b;
  }
};

Then, Webpack can create the complete bundle with only a single .js file as output automatically, and it'll be ready for production with any more post-processing.然后,Webpack 可以自动创建仅包含一个.js文件的完整包,如 output,并且可以通过任何更多的后处理为生产做好准备。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM