简体   繁体   中英

How to import/load entire file to include in my bundle?

How to include an entire file into my bundle main.js?

ES6 can import / export functions and classes. But what if i want to include the whole content from another file into my bundle main.js? how to do it?

I came across the query on Stackoverflow: Managing jQuery plugin dependency in webpack .

I'm not sure about this question though. Those options given there seem to target injecting implicit globals , configuring this , disabling AMD , to include large dists . I don't think this is what i want.

Let's say i have two files in src directory
1- rough.js

const rgh = "qwerty"

2- index.js

import './rough.js' //something like this
console.log (rgh)

Now what i expect in bundle.js is

const rgh = "query";
console.log(rgh)

I just want all the content inside one of my file to get all transported to index.js for webpack to bundle them

Those options given there seem to target injecting implicit globals, configuring this, disabling AMD, to include large dists. I don't think this is what i want.

To understand this you need to understand what webpack is doing for you. Web pack takes a series of Javascript files (and more importantly their contents) and parses these into one file. That's what it does from a file point of view, but if you ignore the file and think about what it does from a code point of view, it takes each one of the imported objects and makes them available to other objects depending upon the rules you define in your code (using import and export ). You can think of this from a closure point of view something like this:

if you have some code like:

import a from 'a.js';

export default b(){
    console.log(a.test());
}

This will be turned into something like, in one js file:

 var a = (function() { var testStr = "test"; function test(){ return testStr; } return {test:test}; })(); var b = (function(a) { console.log(a.test()); })(a);

So you can see that the file isn't really important. What's important is the scope. b can use a because it is injected into it's scope (In this instance as a IIFE).

In the above example a and b are in the global scope but testStr isn't.

So when your talking about "importing my file", you need to forget about that and think about what objects in that file you want to import how. Any variables "in that file" declared directly var a = ....; are in the global scope. So it sounds like what you want to do is import the objects in that file into the global scope .

you just need to import that file in main.js like this way

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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