Webpack basic package installation and sharing, and webpack Basic Package
1. Create a webpack-first folder as the site, create an app folder to store the original js modules (main. js and Greeter. js), and create a publicfile folder to store index.html and the packaged bundle. js file.
1. Find the directory of your project
Npm install-g webpack // install webpack globally
2. initialize the package. json file.
Npm init
3. Install webpack on the site to establish Dependencies
Npm install -- save-dev webpack
4. Compile the Greeter. js File
Module. exports = function (){
Var greet = document. createElement ("div ");
Greet. textContent = "Hi there and greetings ";
Return greet;
}
// Module. exports uses the function as the return value to become a shared module, which can be used as long as the Greeter file is introduced.
5. Compile the main. js File
Var greeter = require ("./Greeter. js ");
Document. getElementById ("root"). appendChild (greeter ());
// Introduce require () ---- Greeter. js Module
// Obtain the html-dom element and place the returned value of the called method in the dom element.
6. Run the command to pack the package,
Webpack app/main. js public/bundle. js
// You can write webpack after it is installed globally. app/main. js is the main file of the portal, public/bundle. js is used to empty the name.
The file is packaged into public, that is, in a directory with html.
Html file code:
<! DOCTYPE html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> first webpack exercise </title>
</Head>
<Body>
<Div id = "root"> </div>
<Script type = "text/javascript" src = "bundle. js"> </script>
// Call the bundle file after Packaging
</Body>
</Html>
II,If there are many modules in the above method, it will be inconvenient. Then we need to execute the entry file and export the package directory every time, so it is easy to make mistakes. Is there any simple way for us to execute a word or make it easier for every package? Here is the method:
Define a configuration file. This configuration file is actually a simple JavaScript module that can put all the information related to the build in it.
Continue with the above example to illustrate how to write this configuration file and create a new file namedWebpack. config. js file, and perform the simplest configuration in it, as shown below, it contains the entry file path and the location where the packaged files are stored
Path.
1. configure it in webpack. config. js.
Module. exports = {
Entry: _ dirname + "/app/main. js", // unique entry file that has been mentioned multiple times
Output :{
Path: _ dirname + "/public", // Where the packaged file is stored
Filename: "bundle. js" // File Name of the output file after Packaging
}
}
Note: "_ dirname" is a global variable in node. js. It points to the directory where the script is currently executed. (If the configuration file is under the app, it points to the app folder)