1、externals

优势

项目中经常使用组件库 改成cdn方式引入 或者单独抽离出来引入
不用每个项目都引入 达到全局组件都可以使用共享

使用

首先在webpack.config.js 中使用externals 定义一个对象
这里的key表示引入import 的名称dom库 value表示引入组件全局变量名

2、cdn引入

  1. externals:{
  2. 'react':"React",
  3. 'react-dom':"ReactDOM",
  4. 'Vue':'vue',
  5. // 'lodash':'lodash',
  6. // 'moment':'moment'
  7. }

cdn引入

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>demo-react</title>
  7. <script src="http://cdn.boot.com/lodash.js"></script>
  8. <script src="http://cdn.boot.com/react.js"></script>
  9. <script src="http://cdn.boot.com/react-dom.js"></script>
  10. </head>
  11. <body>
  12. <div id="root"></div>
  13. </body>
  14. </html>

3、本地引入

  1. externals:{
  2. 'react':"React",
  3. 'react-dom':"ReactDOM",
  4. 'Vue':'vue',
  5. 'lodash':'lodash',
  6. // 'moment':'moment'
  7. }

copy-webpack-plugin

使用copy-webpack-plugin 在webpack.config.js 中plugins配置里添加

  1. new CopyWebpackPlugin([
  2. {
  3. from: path.resolve(__dirname,'static'),
  4. to: path.resolve(__dirname,'dist/static')
  5. },
  6. {
  7. from: path.resolve(__dirname,'dll/vendor.dll.js'),
  8. to: path.resolve(__dirname,'dist')
  9. },
  10. {
  11. from: path.resolve(__dirname,'./node_modules/react/umd/react.production.min.js'),
  12. to: 'js/react.production.min.js'
  13. },
  14. {
  15. from: path.resolve(__dirname,'./node_modules/react-dom/umd/react-dom.production.min.js'),
  16. to: 'js/react-dom.production.min.js'
  17. },
  18. {
  19. from: path.resolve(__dirname,'./node_modules/vue/dist/vue.min.js'),
  20. to: 'js/vue.min.js'
  21. },
  22. ]),

public/index.html引入

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>page-b</title>
  7. <script src="js/react.production.min.js"></script>
  8. <script src="js/react-dom.production.min.js"></script>
  9. <script src="js/vue.min.js"></script>
  10. </head>
  11. <body>
  12. <div id="root"></div>
  13. </body>
  14. </html>

项目使用

项目中这里无需引入react 入口文件已引入了全局react react-dom文件

  1. import './index.scss';
  2. // import React from 'react';
  3. import { render } from 'react-dom';
  4. // class Base extends Component {
  5. // render () {
  6. // return <div>test-base</div>
  7. // }
  8. // }
  9. function Base () {
  10. return <div>
  11. <ul>
  12. <li>1</li>
  13. <li>2</li>
  14. <li>3</li>
  15. <li>4</li>
  16. </ul>
  17. </div>
  18. }
  19. render(<Base/>,document.getElementById('root'));