代码之家  ›  专栏  ›  技术社区  ›  TheUnreal

在单个文件中导入所有Vue JS组件

  •  0
  • TheUnreal  · 技术社区  · 6 年前

    我想将多个Vuejs组件导入到旧项目中。

    目前,我的网站标题中包含了以下脚本:

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
    

    和一个组件文件(我想在不同的文件中分离每个组件)

    <script type="module" src="comp1.js"></script>
    <script type="module" src="comp2.js"></script>
    

    它确实有效,但我想 一个JS文件 这将导入所有其他组件,以便在HTML中将其指向单个JS文件。

    知道吗?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Slim    6 年前

    为您的bundler创建一个文件夹- frontend-dev 例如。

    $ cd frontend-dev
    $ npm init
    

    添加以下依赖项

    "devDependencies": {
        "@babel/core": "^7.2.2",
        "@babel/preset-env": "^7.3.1",
        "babel-loader": "^8.0.5",
        "webpack": "^4.29.3",
        "webpack-cli": "^3.2.3"
      }
    
    $ npm install
    

    创造 webpack.config.js 使用以下最小配置:

    let path = require('path');
    
    module.exports = {
    
      output: {
          path: p('../public'), // where to create bundles files
          publicPath: '/public/', // public path to the created files
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader",
              options: {
                presets: ['@babel/preset-env']
              }
            }
          },
        ]
      },
    };
    
    /**
     * Path.resolve alias curried with current directory (__dirname)
     * as first parameter
     */
    function p(){
      return path.resolve(__dirname, ...arguments)
    }
    
    

    前端开发 创建文件夹 src index.js 其中:

    // index.js
    import '../../comp1.js'
    import '../../comp2.js'
    

    添加 "build": "webpack" 脚本部分中的命令 package.json 然后跑 npm run build 在指定的public目录中查看bundled.js文件。

    你可以用 require.context 要导入目录中的所有文件,请参见 webpack docs .