【问题标题】:How to extract JS and CSS from Vue single file to *.js and *.css如何从 Vue 单个文件中提取 JS 和 CSS 到 *.js 和 *.css
【发布时间】:2020-10-19 07:44:33
【问题描述】:

假设我写了一个组件a.vue,webpack打包后,一些使用过a.vue的HTML看起来是这样的:

......
<script src="page.js"></script>
<link href="page.css" rel="stylesheet"/>
......

a.Vue中的JS和CSS被打包成page.jspage.css。我想知道如何将JS和CSS提取到单独的文件中。那么HTML看起来像:

<script src="a.js"></script>
<script src="page.js"></script>
<link href="a.css" rel="stylesheet"/>
<link href="page.css" rel="stylesheet"/>

我知道这样做不好,我只想知道怎么做。

【问题讨论】:

    标签: javascript vue.js webpack vue-loader


    【解决方案1】:

    使用vue-cli创建项目,然后它可以自动提取css和js。

    我正在检查它的 webpack 配置

    【讨论】:

      【解决方案2】:

      我个人喜欢单文件组件 (SFC),但使用 Vue 分离 html、css 和 js 真的很容易。

      MyComponent.vue

      <template>
        // html
      </template>
      
      <script src="./MyComponent.js"></script>
      <style scoped src="./MyComponent.css">
      </style>
      

      See a simple example on Codesandbox

      【讨论】:

      • 谢谢,但我试过这样。它不起作用。能发一下webpack配置吗
      【解决方案3】:

      我在 github 上发现了一个类似的问题。也许您可以尝试给定的解决方案

      https://github.com/vuejs/vue-loader/issues/681

      configure webpack.prod.conf.js
      config.entry = {}
      config.entry[one.name] = one.path
      config.output.libraryTarget = 'umd'
      config.output.library = `${namespace}${one.importName}`
      config.output.filename = `index.min.js`
      config.output.path = path.resolve(__dirname, `../dist/components/${one.name}/`)
      

      构建它
      webpack(config, function (err, stats) {})
      

      【讨论】:

        猜你喜欢
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-06
        • 2015-05-17
        • 2019-12-06
        • 2012-08-11
        • 2011-02-17
        相关资源
        最近更新 更多