I’ve done this in my last article: Webpack4 creating a project and packaging a JS file.
1. Create a folder webpack and use the command line CD to go to this folder
$ cd /webpack
Copy the code
2. Initialize
$ npm init
Copy the code
3, if not installed webpack, webpack-CLI can see the top article to install.
4. Install webpack-dev-server
$ npm install webpack-dev-server --save-dev
Copy the code
5, After installation, create a main.js file in the current directory with the following contents:
console.log('dzm');
Copy the code
6, we used to create a new webpack.config.js to configure the text, in fact, now distinguish the environment is almost the same, here I record two ways
1) Add scripts to package.js to configure serve and build, and then they correspond to different configuration files. The configuration files can be written separately. In this way, they can be packaged directly through different configuration files:
"scripts": {
"serve": "webpack --config build/dev.js",
"build": "webpack --config build/pro.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Copy the code
In dev.js and pro.js, you only need the same configuration to write different files. You can directly export different package names in the two files to test:
Var config = {// entry file entry: {main: './main.js'}, // output configuration output: {// output the resulting filename can be arbitrary filename: 'xyq.js'}};Copy the code
File effect:
2) add scripts to package.js to configure serve and build. Use webpack-dev-server to differentiate between serve and build.
"scripts": {
"serve": "webpack-dev-server --env development --config build/conf.js",
"build": "webpack-dev-server --env production --config build/conf.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Copy the code
Then we create a new conf.js file, which can be processed in it. I am using the merge configuration file, so I need to install webpack-Merge
$ npm install webpack-merge --save-dev
Copy the code
In conf.js, I still keep the method of distinguishing configuration files in the first solution, and merge the configurations of different configuration files with the public configuration after judging the environment
// const devConfig = require('./dev') // const proConfig = require('./pro' --save-dev const marge = require('webpack-merge') var pubConfig = env => {// Return {// entry file entry: {main: './main.js'}, // output configuration output: {// output the resulting filename can be arbitrary filename: 'xyq.js'}}}; / / module according to the judgment to distinguish environment. Exports = env = > {/ / env is pageage here. Js - behind the env configured parameters, development and production let config = env === 'production' ? Return merge(pubConfig(env), config)};Copy the code
File effect:
7. Select one of the above to test and run the command
$NPM run build $NPM run buildCopy the code