The preparatory work
Before the project begins, you need to install the dependencies of Rollup.
npm i -D rollup @babel/core @babel/preset-env rollup-plugin-babel
Copy the code
Here, a brief description of each of the above dependencies is given:
- Rollup: A JavaScript module wrapper that compiles small pieces of code into larger complex pieces
- Babel /core: Analyze JS code into AST, which is convenient for each plug-in to analyze the syntax for corresponding processing
- @babel/preset-env: is a smart preset that uses the latest ES6/7 syntax, regardless of the target environment
- Rollup-plugin-babel: Perfect combination of Rollup and Babel
Write the rollup configuration file
Create entry file
To build an environment that can run ES6 syntax, you need an entry file. I create a SRC directory in the root directory, and create an index file in the directory.
Then write some simple ES6 code in this file to facilitate rollup packaging.
let a = 1;
console.log(a);
export default a;
Copy the code
Configuration file writing
Create the rollup.config.js file in the root directory. In this file we will normally configure the following:
- Input: Address of the entry file
- Output: indicates the configuration item of the output file
- Umd: Support for AMD and CommoJS specifications
- Name: Indicates the name of the package
- File: directory of the package
- Sourcemap: After packaging, do the code mapping to find the ES6 code based on ES5
- The most common is to configure Babel
The specific code is as follows:
import babel from 'rollup-plugin-babel';
export default {
input: './src/index.js'.output: {
format: 'umd'.name: 'Vue'.file: 'dist/vue.js'.sourcemap: true
},
plugins: [
babel({
exclude: 'node_modules/**'}})]Copy the code
Babel’s configuration
The default for Babel in Rollup is not written directly to the configuration file like webpack. Instead, it has to be written as a “.babelrc “.
So you need to create a.babelrc file in the root directory.
In Babelrc, you need to configure a set of plug-ins. The set of plug-ins is called a default. Babel packaging requires parsing by default.
The specific contents of the file are as follows:
{
"presets": [
"@babel/preset-env"]}Copy the code
Run packaging
Finally, add the script to run in package.json.
"scripts": {
"serve": "rollup -c -w"
},
Copy the code
Then execute the command:npm run serve
, you will see the following interface:
At this point, the index.js file is packaged. A dist directory will appear in the root directory.
At this point, a recommended es6-enabled packaging environment is configured.