当我们按照chrome插件要求的格式创建文件夹后,发现本地js无法拆分为多个js进行引入使用,本地代码也是无法打包,那么如何可以将一个大的js文件分解为多个js文件,并进行引用呢?如何将本地的图片,css,html一并进行打包呢?
一.打包js
1.使用webpack:
npm install --save-dev webpack webpack-cli
本地创建:webpack.config.js,内容如下:
const path = require('path'); module.exports = { entry: { contentScript: './src/content-script.js', }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, ], }, };
注意:其他地方若需要引入js,则需要引入打包后的文件dist中的js
2.使用babel
npm install --save-dev @babel/core @babel/preset-env babel-loader
本地创建.babelrc,内容如下:
{ "presets": ["@babel/preset-env"] }
3.创建package.json,在里面补充内容如下
"scripts": { "build": "webpack --mode production" },
然后可以通过命令:npm run build 进行打包
二.打包css
1.安装mini-css-extract-plugin
npm i mini-css-extract-plugin
2.webpack.config.js中补充代码如下
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
rules:[ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], }, ], plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', }), ],
三.打包图片
1.安装file-loader
npm i file-loader
2.webpack.config.js中补充代码如下
rules:[ { test: /\.(png|jpe?g|gif|svg)$/i, use: [ { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'images', // Output images to the 'images' folder in the 'dist' directory }, }, ], }, ]
四.打包html
1.安装copy-webpack-plugin
npm i copy-webpack-plugin
2.webpack.config.js中补充代码如下
const CopyPlugin = require('copy-webpack-plugin'); plugins: [ new CopyPlugin({ patterns: [ { from: 'src/popup.html', to: 'popup.html', }// Add other files to copy if needed ], }), ],
五.打包manifest.json
1.安装copy-webpack-plugin
npm i copy-webpack-plugin
2.webpack.config.js中补充代码如下
const CopyPlugin = require('copy-webpack-plugin'); plugins: [ new CopyPlugin({ patterns: [ { from: 'src/manifest.json', to: 'manifest.json' }, // Add other files to copy if needed ], }), ],